Net Core NLog.Web “aspnet-user-identity” is empty?

吃可爱长大的小学妹 提交于 2020-06-27 08:16:40

问题


I was using "NLog.Extensions.Logging" for logging and need to log user identity and found that it is possible with "NLog.Web.AspNetCore". "nlog.config" file is configured to log the "aspnet-user-identity". However, when I look at logs, user identity part is always empty string, the other columns are look pretty good. Am I missing something?

A part of my configuration file is here:

<extensions>
  <assembly="NLog.Web.AspNetCore" />
</extensions>

<parameter name="@identity" layout="${aspnet-user-identity}"/>

<logger name="*" minlevel="Trace" appendTo="database"/>

And an insert command insert a log to db with "@identity" parameter, but it is always empty like I said.


回答1:


I think I have found the issue,

There was an breaking change, The IHttpContextAccessor service is not registered by default anymore. (See announcement)

So add in your startup.cs:

public void ConfigureServices(IServiceCollection Services)
{
    //call this in case you need aspnet-user-authtype/aspnet-user-identity
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}



回答2:


Accepted answer didn't worked for my case (using JwtSecurityToken on ASP.NET Core 3.1), Later realized that I just forgot to add the ClaimTypes.Name on my JwtSecurityToken Claims.

Now its working and no need to register IHttpContextAccessor.




回答3:


I found this question while searching for "asp.net core nlog username". Eventually I found the solution and I am logging it here for posterity.

Problem

How do I include the currently logged in user's username in my NLog log messages?

Solution

I am using NLog inside of my ASP.NET Core web app. I tried using the ${aspnet-user-identity} layout renderer, but determined that the value was empty because we were using custom authentication.

After doing some digging, I figured out that I could access values stored as a ASP.NET Session variable from NLog. So, after I authenticated the user, I stuffed their username into a session variable and voila!

Here is the code I call after authenticating the user:

// Store username in session so we can access it from NLog logs.
httpContext.Session.SetString("NlogUser", contact.Username);

Here is what the layout renderer line in the nlog.config looks like

<parameter name="@identity" layout="${aspnet-session:variable=NlogUser}"/>

Here is the corresponding NLog documenation for the AspNetSession layout renderer.



来源:https://stackoverflow.com/questions/40715331/net-core-nlog-web-aspnet-user-identity-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!