TraceId, RequestId, and TraceIdentifier in ASP.NET Core - asp.net-core

I'm wondering how ASP.NET Core and Microsoft.Extensions.Logging assigns TraceId, RequestId, and TraceIdentifier. When looking through my log after making a request to my website I see the following information logged from Microsoft.Extensions.Logging:
TraceId: e57eb4708135dd43a914ee9e98165b1b
RequestId: 80000389-0006-ee00-b63f-84710c7967bb
I also log errors happening from ASP.NET Core through custom middleware. On the same request as above I see an error in the same log with the following information:
TraceIdentifier: 80000389-0006-ee00-b63f-84710c7967bb
The value 80000389-0006-ee00-b63f-84710c7967bb looks like the request GUID assigned by ASP.NET Core which makes sense when looking at the RequestId property from Microsoft.Extensions.Logging. But ASP.NET Core logs the request id as TraceIdentifier which feels a little weird.
I would personally prefer having the value from Microsoft.Extension.Logging's TraceId in the TraceIdentifier property when doing custom logging from ASP.NET Core middleware. Any input would be appreciated.
Update - Since writing this question I did create an issue on GitHub which were pretty much ignored and then closed because of inactivity :( https://github.com/dotnet/aspnetcore/issues/31747

Related

.Net Core DenyAnonymousAuthorization Requirement error

I m getting a 401 error status with this message while trying to retrieve some data from another Net core 5 Web api :
"Authorization failed. These requirements were not met:DenyAnonymousAuthorizationRequirement: Requires an authenticated user.."
On the Web api I m using a windows authentification :
services.AddAuthentication(HttpSysDefaults.AuthenticationScheme);
I cannot found many documentation on this kind of authentification, and I don't think that I miss something Any thoughts please ?
Try swapping around the calls where it is first setup.
app.UseAuthentication(); app.UseAuthorization();
I had the same error where everything else looked fine. Until I swapped these around I kept getting this issue trying to access the endpoint using a token.

Nonce cookie not being returned in Code flow, .AspNetCore.Identity.Application cookie returned instead

We have upgraded both our application running openiddict and the client application in question to .net core 3.1 and .net framework 4.8 respectively. Openiddict is also updated to 3.1.0
Since this update, and the resulting changes in both projects, our .net framework asp.net mvc 5 application began hitting exception
IDX21323: RequireNonce is 'System.Boolean'. OpenIdConnectProtocolValidationContext.Nonce was null, OpenIdConnectProtocol.ValidatedIdToken.Payload.Nonce was not null. The nonce cannot be validated. If you don't need to check the nonce, set OpenIdConnectProtocolValidator.RequireNonce to 'false'. Note if a 'nonce' is found it will be evaluated.
Upon inspection of the redirect request from our connect/authorize endpoint back to the client application's signin callback (called signin-sevanidentity) we see that instead of receiving a cookie of OpenIdConnect.nonce like we see on our production instance we see .AspNetCore.Identity.Application which is not being recognized by the client
Callback in updated version:
OpenIdConnect.nonce Header Info
Callback in working production instance:
ProductionHeaderInfo
Not certain if I've messed up config in openiddict, the client or both.
I found the resolution for this specific issue. The root cause was because I was using the incorrect response type in my client side's OpenIdConnect configuration. I was using "code id_token" instead of "code"
When I went to modify the OpenIdConnectResponseType enum value I found that code was not one of them, only 2 options were.
It turns out I had mistakenly installed an unneeded package that overrode the extensions.
Microsoft.IdentityModel.Protocol.Extensions published by "Microsoft Corporation" not "Microsoft"
Nuget Package name and version
After uninstalling this package I was able to add the code response type as intended.

Any alternatives to aspnet-request:serverVariable when using NLog with .Net Core?

As stated on the NLog GitHub the ${aspnet-request:serverVariable=String} layout renderer is not supported in .Net Core.
The documentation doesn't provide alternatives to many of the variables available under serverVariable.
My question is, are there any alternatives? Like to access remote address, server name, port etc? Or do I just have to write a bunch of custom layout renderers documented here and dependency inject all the stuff by hand?
For ASP.NET Core there as many new layout renders. The reason is that the API of ASP.NET Core is very different and the server variables can't be read like in ASP.NET (so non-core)
There are currently 13 layout renders for ASP.NET Core that renders a part of the request.
${aspnet-request} - ASP.NET Request variable.
${aspnet-request-contenttype} - ASP.NET Content-Type header (Ex. application/json)
${aspnet-request-cookie} - ASP.NET Request cookie content.
${aspnet-request-form} - ASP.NET Request form content.
${aspnet-request-headers} - ASP.NET Header key/value pairs.
${aspnet-request-host} - ASP.NET Request host
${aspnet-request-ip} - Client IP.
${aspnet-request-method} - ASP.NET Request method (GET, POST etc).
${aspnet-request-posted-body} - ASP.NET posted body / payload
${aspnet-request-querystring} - ASP.NET Request querystring.
${aspnet-request-referrer} - ASP.NET Request referrer.
${aspnet-request-url} - ASP.NET Request URL.
${aspnet-request-useragent} - ASP.NET Request useragent.
See also https://nlog-project.org/config/?tab=layout-renderers&search=package:nlog.web.aspnetcore
If you need something else, you could indeed create a custom renderer. If you need the http request you could use:
AspNetLayoutRendererBase.Register("aspnet-request-myrenderer", (logevent, httpcontext, config) => ... );
You need to reference the NLog.Web.AspNetCore package for that.

WebApi Core 2.2 OData resource/path not found

I'm using WebApi Core 2.2. The Microsoft OData Client is adding a new parent record plus a subrecord (Deal+DealFee) from a WPF application. I'm hosting in IIS on Windows 10.
When I call container.SaveChanges(), it successfully calls the service to add the parent Deal record, but then it does a SECOND POST operation to this url (this is generated by the MS odata client lib):
POST http://localhost/mysite/odata/Deals(14)/DealFees
(note this includes the ID 14 which was just generated when adding the Deal)
This is two separate POSTs from the MS odata client lib, not a "deep insert" apparently. However, this results in a 404 (NotFound), which I can observe in Fiddler. The following urls DO work perfectly:
/odata/Deals
/odata/Deals(14)
/odata/DealFees
It seems like either the WebApi Core 2.2 service is not handling the POST to /Deals(14)/DealFees path, OR /Deals(14)/DealFees isn't a valid odata Uri? Is this kind of path generally supported in OData?
I don't know. Can anyone shed some light on what's going on?
Deep insert is not supported in WebAPI OData as of now. To me, it seems like the client is updating the resource set and the resource set for the navigation with two separate post requests and the reason you are getting a 404 is that there is no action mapped to the second request URI in the service.
The service can support this either by introducing a PostToDealFeesFromDeals controller action with default OData routing convention or use attribute routing to map the action for such requests.
If the action already exists then it might be that the first request did not finish creating the new record and the second request was fired, hence 404.

Error management in ASP.NET Core using a BaseController

In previous ASP.NET versions I was used to create a BaseController inherited from the other controllers and there intercepting the general error and logging each error with a simple logging method and passing the ExceptionContext filterContext.
Should I do the same in ASP.NET 5?
I see in file Startup.cs that there is a if/else statement that basically separate the debug/live condition, with line
app.UseErrorHandler("/Home/Error");
for a production application.
How am I supposed to hook in the process and log the errors?
Handling and logging errors in ASP.NET 5 involves a few elements.
To handle the error in a production scenario and show an error page, the app.UseExceptionHandler() method is the way to go. The Diagnostics repository on the ASP.NET GitHub organisation includes a sample that shows this. For development-time scenarios where you want to see a full stack trace and other diagnostic information, use app.UseDeveloperExceptionPage() as seen in this sample.
If the application is using ASP.NET MVC 6, then there is an MVC-specific way of handling errors, much as there was in earlier versions of ASP.NET MVC. In ASP.NET MVC 6, a filter (or the Controller itself, which is also a filter) can handle/override the OnActionExecuted method and inspect the ActionExecutedContext parameter to attempt to handle the error.
When it comes to logging, there's a new logging infrastructure in ASP.NET 5 that reports a great deal of information to any registered ILogger. The default project templates in Visual Studio 2015 register some loggers that log errors (and other data) to the console and the Visual Studio debug output window. However, when running in IIS or IIS Express there is no console window (yet!). But if you run from the command line (using dnx web) then you'll see the error. Or, of course, you can register a different logger that writes to a log file or database and see the logs there.
To register a custom ILogger in a web app:
Write a logger that implements the ILogger interface. See the DNX implementations for how to do this.
Add a parameter of type ILoggerFactory to your app's Startup class's Configure method.
In the Configure method call loggerFactory.AddProvider(<some provider>) and pass in an instance of your logger.