I have a ASP.Net 4.5 application that I am trying to upgrade to ASP.Net Core. This application receives calls from a 3rd party application.
In my old application I have an action that looks like this:
public async Task<HttpResponseMessage> RealTimeAsync(HttpRequestMessage request)
{
var StatusMessage = string.Empty;
try
{
var doc = new XmlDocument();
doc.Load(await request.Content.ReadAsStreamAsync());
From 4.5 this works fine. However, when I use this code in ASP.Net core I get an "Object Reference Not Set to an Instance of an Object" error because request.Content is null.
The requests coming in to the two applications (4.5 and .Net Core) are the same. Why is request.Content null in my .Net Core application?
When I referenced this post: ASP.NET Core HTTPRequestMessage returns strange JSON message
I tried installing the suggested Nuget Package. However, it is not compatible with .Net Core:
error: Package Microsoft.AspNet.WebApi.Client 5.2.2 is not compatible
with netcoreapp1.0 (.NETCoreApp,Version=v1.0). Package
Microsoft.AspNet.WebApi.Client 5.2.2 supports: error: - net45
(.NETFramework,Version=v4.5) error: -
portable-net45+netcore45+wp8+wp81+wpa81
(.NETPortable,Version=v0.0,Profile=wp8+netcore45+net45+wp81+wpa81)
error: One or more packages are incompatible with
.NETCoreApp,Version=v1.0.
That code needs to be refactored to use more recent structure.
public Task<IActionResult> RealTimeAsync() {
var StatusMessage = string.Empty;
try {
var request = this.Request;
var doc = new XmlDocument();
doc.Load(request.Body); //request.Body returns a stream
//...other code...
Related
I'm having the above error after running an azure function called "Test" that redirects to an external URL of a service we want to use.
[FunctionName("Test")]
public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req)
{
Log.Information("C# HTTP trigger function processed a request.");
string url = _authenticationService.GetAuthorizationUri().ToString();
return new RedirectResult(url);
}
The site at the URL prompts the user to authorize use of their data and performs a redirect to the previously authorized url of our "AuthorizationCallback", along with a query string parameter.
[FunctionName("AuthorizationCallback")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req)
{
Log.Information("C# HTTP trigger function processed a request.");
string code = req.Query["code"];
try
{
if (!string.IsNullOrEmpty(code))
{
await _authenticationService.ExchangeCodeForAccessToken(code);
return new OkResult();
}
}
catch (System.Exception)
{
return new UnauthorizedResult();
}
return new NotFoundResult();
}
The AuthorizationCallback function is hit but produces the following error in the console:
These are the dependencies of the current project on the solution (which is set as the startup project):
I've tried installing both the latest stable version (5.0.0) and the version before that (3.1.13) of Microsoft.Extensions.Primitives in the current project, but I'm still getting the same error. I've noticed the package that can't be loaded is within microsoft.azure.webjobs (3.0.23), which is within microsoft.azure.webjobs.extensions.storage (4.0.4), but these are used in another project entirely, for another azure function (blob triggered). Any ideas on how to overcome this error? Thank you all.
The Azure Functions host for .NET Core 3 uses an in-process hosting model, which essentially means you are limited in what versions of Microsoft assemblies you can use. What's happening is that something in your project has a reference to a newer version of Microsoft.Extensions.Primitives, but an older version of that library is already loaded by the Azure Functions host application.
For Azure Functions .NET Core 3, you should restrict all Microsoft.Extensions.* libraries to v3.x. You currently have Microsoft.Extensions.DependencyInjection 5.0.1, which should be changed to 3.x. Check for any other Microsoft.Extensions.* libraries either at the Packages level or anywhere beneath (tip: you can find them quickly by putting Microsoft.Extensions in the input box at the top of the Solution Explorer). You may need to downgrade some other library that has Microsoft.Extensions.Primitives as a dependency.
You might also be able to get away with manually writing a bindingRedirect pointing the newer version to an older version. The Microsoft.Extensions.* packages are relatively stable across versions, so that may work. It would make me very nervous, though.
I am trying to access AWS multi region access point using S3 SDK, but have this error when making request:
MarshalDirectiveException: Marshalling of non-string and non-blittable
arrays to managed code is not implemented. (wrapper native-to-managed)
Aws.Crt.Auth.AwsSigner.OnHttpRequestSigningComplete(ulong,int,intptr,ulong,intptr,intptr,unit)
Here is the code:
Config = new AmazonS3Config();
Config.UseArnRegion = false;
Config.RegionEndpoint = RegionEndpoint.EUWest2;
Client = new AmazonS3Client(Config);
GetObjectRequest req = new GetObjectRequest
{
BucketName = arn:aws:s3::123456789012:accesspoint/<MRAP_alias>,
Key = filename
};
Client.GetObjectAsync(req).Wait();
Everything works fine when I make a request to the bucket directly or when I use CLI.
It seems that the problem could be with the .NET version. I tested it with .NET Core 3.1 and it worked, but the project is made on Unity, and Unity is limited to .NET Standard 2.1 and .NET Framework 4.x
Current versions:
AWSSDK.Core.3.7.13.12 AWSSDK.S3.3.7.9.61 AWSSDK.Extensions.CrtIntegration.3.7.1.4
I have the following method:
public static WorkItem GetWorkItem(int workItemId, bool relations)
{
Uri accountUri = new Uri(URL);
string personalAccessToken = PERSONAL_ACCESS_TOKEN;
VssConnection connection = new VssConnection(accountUri, new VssBasicCredential(string.Empty,
personalAccessToken));
var client = connection.GetClient<WorkItemTrackingHttpClient>();
WorkItemExpand? expand = relations ? WorkItemExpand.Relations : (WorkItemExpand?)null;
return client.GetWorkItemAsync(workItemId, null, null, expand).Result;
}
Basically I am using the Microsoft.TeamFoundationServer.Client nuget package to get a workitem from our companies Azure Devops project.
Most of the time this method works fine, however occasionally (Meaning once in every five or so attempts) the client.GetWorkItemAsync() method will fail with the error:
Message:"One or more errors occurred. (The SSL connection could not be established, see inner exception.)"
Source:"System.Private.CoreLib"
InnerException:
{
Message:"Authentication failed because the remote party has closed the transport stream."
Source:"System.Net.Security"
InnerException:null
}
This has only started occuring after I updated my project from targeting Dot Net Core 2.1 to Dot Net Core 3.1
My question is what can I do to solve this issue? Is this an problem with Microsoft's Microsoft.TeamFoundationServer.Client nuget package, or am I doing something wrong?
As a temporary solution I seem to be able to simply repeatedly call the method until it works but I would rather not have to do that.
Any help is appreciated, Thanks.
EDIT:
To further test this issue I downgraded my project from Dot Net Core 3.1 to Dot Net Core 2.1 and ran the method 10 times and it never threw any error. No code changes. Then, I upgraded my project from Dot Net Core 2.1 back to Dot Net Core 3.1 and ran the method. I Immediately got this error again.
Unless I am missing something, I can only conclude somehow the Dot Net Core change has broken this method.
I'm having some strange behavior in my .NET Core 2.2 application.
When trying to make an HTTP request (through either HttpClient or RestSharp), as long as the site that I am requesting is hosted on a different server than where my calling application resides, I receive a 200 response, just like I'd expect, which is great.
However, as soon as I try to hit a site on the same server (and I've tried this with the exact same site hosted on both servers), I get a 401 Unauthorized.
For reference, the site that I am requesting is a ASP.NET Web API on .Net Framework, and it uses Windows Auth.
I've tried this in .Net Framework 4.6.2 and .Net Core 3.0, and both of them work fine, and do not exhibit this problem -- it seems just to affect 2.2 for me.
I know there is the "Loopback Check Issue", however if this was the case, I'd expect .Net Framework and .Net Core 3.0 to face the same problem.
I also am aware of This GitHub Issue however that seems to have been solved in 2.2.
For reference here is some sample code that demonstrates the problem with HttpClient (The same codes is used for all versions of .Net)
static async Task Main(string[] args)
{
await MakeRequest();
}
public async static Task MakeRequest()
{
Console.WriteLine("Enter URL:");
var url = Console.ReadLine();
var uri = new Uri(url);
try
{
var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });
var res = await client.GetAsync(uri);
res.EnsureSuccessStatusCode();
var content = await res.Content.ReadAsStringAsync();
Console.WriteLine(res.StatusCode);
Console.WriteLine(content);
}
catch (Exception e)
{
Console.WriteLine($"Error: {e}");
}
finally
{
await MakeRequest();
}
}
Any ideas?
EDIT:
SDK used: 2.2.104
Runtime used: 2.2.5
2.2.5 seems to be the version of .NET core runtime version instead of .NET CORE SDK version.
The latest version of 2.2 sdk is 2.2.4.
Since 2.2.7 would be the update verion of 2.2.5 and this issue is not happening in runtime 2.2.7. Is it acceptable to just update runtime 2.2.7 on your server?
As stated in official document, I am trying to implement UseOwin in the Startup.cs.I am trying to use/port IAppBuilder (Microsoft.Owin.Builder.AppBuilder) inside IApplicationBuilder (Microsoft.AspNetCore.Builder.IApplicationBuilder). I had legacy code written using IAppBuilder running fine on .Net Framework 4.5.
I have seen couple of examples about using IAppBuilder in IAplicationBuilder e.g. example 1 example 2. These attempts were about .netcore 1.1 and not .net core 2.0. May be this is the reason i am unable to port.
Please share your thoughts whether i am trying to achieve something not possible at the moment in .net core 2.0 or there is some error in my code.
Note:
I am using dotnetcore 2.0 with Visual Studio 2017
Error
I am getting following error.
return owinAppBuilder.Build,
Task>>(); TypeLoadException: Could not load type
'System.Security.Cryptography.DpapiDataProtector' from assembly
'System.Security, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'.
My attempt
app.UseOwin(setup => setup(next =>
{
var owinAppBuilder = new AppBuilder();
var aspNetCoreLifetime =
(IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));
new AppProperties(owinAppBuilder.Properties)
{
OnAppDisposing = aspNetCoreLifetime?.ApplicationStopping ?? CancellationToken.None,
DefaultApp = next,
AppName = "test"
};
// Only required if CORS is used, configure it as you wish
var corsPolicy = new System.Web.Cors.CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
AllowAnyOrigin = true,
SupportsCredentials = true
};
//corsPolicy.GetType()
// .GetProperty(nameof(corsPolicy.ExposedHeaders))
// .SetValue(corsPolicy, tusdotnet.Helpers.CorsHelper.GetExposedHeaders());
owinAppBuilder.UseCors(new Microsoft.Owin.Cors.CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(corsPolicy)
}
});
PublicClientId = "self";
OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new Microsoft.Owin.PathString("/Login"),
Provider = new MyServiceProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
AllowInsecureHttp = true,
RefreshTokenProvider = new MyRefreshTokenProvider(),
};
owinAppBuilder.UseOAuthBearerTokens(OAuthOptions);
//owinAppBuilder.UseTus(context => new DefaultTusConfiguration
//{
// // Excluded for brevity, use the same configuration as you would normally do
//});
return owinAppBuilder.Build<Func<IDictionary<string, object>, Task>>();
}));
Microsoft.Owin and related packages do not have targets for .NET Core, no for .NET Standard. All they have is dlls targeting full .NET. You can reference such libraries from your project targeting .NET Core, but they are not guaranteed to work, as you see yourself, because API (set of classes\methods\signatures) of full .NET and .NET Core are different. Visual Studio even will show a warning when you are doing that, for example:
Package 'Microsoft.Owin 3.1.0' was restored using
'.NETFramework,Version=v4.6.1' instead of the project target framework
'.NETCoreApp,Version=v2.0'. This package may not be fully compatible
with your project.
There is Microsoft.AspNetCore.Owin package and you can use OWIN middleware in .NET Core app as your first link describes, but almost all it provides is UseOwin extension method. There is no AppBuilder type there and so on, and there are no Microsoft.AspNetCore.Owin.Cors packages or similar. So you have to either implement all that yourself (no reason to, because you can use the same functionality provided by asp.net core framework) or wait for OWIN packages that target .NET Standard\Core and do that (didn't check, maybe they even exist already).
So, your code uses packages which are indeed not compatible with your target framework, as exception you have at runtime shows. So another answer (for some reason downvoted) is technically correct.
If you still want to use those packages reliably - you need to target full .NET Framework and not .NET Core. To do that, open your .csproj file and change
<TargetFramework>netcoreapp2.0</TargetFramework>
To some .NET framework version that supports .NET Standard 2.0, for example:
<TargetFramework>net47</TargetFramework>
Then go to nuget package manager and, if you have microsoft.aspnetcore.all package (or other packages targeting .NET Core) - uninstall it, you don't need it anyway. Then install Microsoft.AspNetCore package and all other asp.net core packages you need (if not installed already). Rebuild, run and it will work just fine.
That works because all (most?) AspNetCore packages target .NET Standard, not .NET Core, and you can use them in projects targeting full .NET Framework.
Note that by doing that you have asp.net Core project, but not on .NET Core, with all consequences that come from that (cannot run with dotnet run, on linux need to run with mono, and so on).
The Microsoft.Owin components will not work on dotnet core 2.0, they only work on .NET 4.5+