gpt4 book ai didi

c# - NLog .NET Core aspnet-user-identity 始终为空

转载 作者:太空宇宙 更新时间:2023-11-03 12:09:55 24 4
gpt4 key购买 nike

我已经阅读了一堆主题相似的 SO 帖子,似乎没有一个能解决我的问题。

我的 nlog.config 类似于:

<?xml version="1.0" encoding="utf-8"?>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xsi:schemaLocation="NLog NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwExceptions="true"
internalLogIncludeTimestamp="true"
internalLogFile="nlog-internal.log"
internalLogLevel="Error">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<target xsi:type="Database"
name="database"
commandType="Text"
dbProvider="Npgsql.NpgsqlConnection, Npgsql"
connectionString="${var:appDbConnectionString}"
commandText="Layout">
<commandText>
insert into "logs" ("application", "user", "level", "message", "exception", "logger")
values (@application, @user, @level, @message, @exception, @logger);
</commandText>
<parameter name="@application" layout="My App" />
<parameter name="@user" layout="${aspnet-user-identity}" />
<parameter name="@level" layout="${level}" />
<parameter name="@message" layout="${message}" />
<parameter name="@exception" layout="${exception:format=tostring}" />
<parameter name="@logger" layout="${logger}" />
</target>
</targets>
<rules>
<logger name="MyApp.*" minlevel="Info" writeTo="database" final="true" />
<logger name="*" minlevel="Error" writeTo="database" final="true"/>
<logger name="*" minlevel="Warn" writeTo="database" final="true"/>
</rules>
</nlog>

...我的 Startup.csConfigureServices() 方法中调用它:

services.AddLogging();

...我的 Startup.csConfigure() 方法中调用它:

var loggerFactory = app.ApplicationServices.GetService<ILoggerFactory>();
LogManager.LoadConfiguration("nlog.config");
LogManager.Configuration.Variables["appDbConnectionString"] =
config["ConnectionStrings:ApplicationContext"];
loggerFactory.AddNLog();

...我的 Program.cs 中的 BuildWebHost(string[] args) 有:

public static IWebHost BuildWebHost(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseNLog()
.Build();
}

我的 ClaimsPrincipal 已正确填写并配置了经过身份验证的用户,但我无法{aspnet-user-identity} 设为空白以外的任何内容。 p>

我做错了什么?

我正在使用 NLog 4.5.10、NLog.Extensions.Logging 1.3.0 和 NLog.Web.AspNetCore 4.7.0;这些似乎是最新的库。

最佳答案

事实证明,当 NLog 与 IoC 容器一起使用时,它实现了自己的服务定位器。我需要像这样添加一行:

app.ApplicationServices.SetupNLogServiceLocator();

...奇迹发生了。我不得不写一个 issue in GitHub为此,他们几乎立即做出了回应

关于c# - NLog .NET Core aspnet-user-identity 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52884266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com