简体   繁体   English

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

[英]NLog .NET Core aspnet-user-identity always empty

I've read a bunch of similarly-themed SO posts, none seem to address my issue.我已经阅读了一堆类似主题的 SO 帖子,但似乎没有一个能解决我的问题。

My nlog.config resembles this:我的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>

... my Startup.cs invokes this in the ConfigureServices() method: ...我的Startup.csConfigureServices()方法中调用它:

services.AddLogging();

... my Startup.cs invokes this in the Configure() method: ...我的Startup.csConfigure()方法中调用它:

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

... my BuildWebHost(string[] args) in my Program.cs has: ......我BuildWebHost(string[] args)在我Program.cs有:

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

My ClaimsPrincipal is properly filled out and configured with authenticated users, but I cannot get the {aspnet-user-identity} to be anything other than blank.我的 ClaimsPrincipal 已正确填写并使用经过身份验证的用户进行配置,但我无法{aspnet-user-identity}设置为空白。

What am I doing wrong?我究竟做错了什么?

I'm using NLog 4.5.10, NLog.Extensions.Logging 1.3.0, and NLog.Web.AspNetCore 4.7.0;我正在使用 NLog 4.5.10、NLog.Extensions.Logging 1.3.0 和 NLog.Web.AspNetCore 4.7.0; these seem to be the latest libraries.这些似乎是最新的库。

SO IT TURNS OUT that NLog implements its own Service Locator when using it with IoC containers.所以事实证明,当 NLog 与 IoC 容器一起使用时,它实现了自己的服务定位器。 I needed to add a line like so:我需要像这样添加一行:

app.ApplicationServices.SetupNLogServiceLocator();

...and magic happened. ……魔法发生了。 I had to write an issue in GitHub for it, but they responded almost instantly我不得不为此在 GitHub 上写了一个问题,但他们几乎立即做出了回应

loggerFactory.AddNLog(); is the issue.是问题。

Change your program.cs to this:将您的 program.cs 更改为:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder
                    .CaptureStartupErrors(true)
                    .UseIISIntegration()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseStartup<Startup>()
                    .ConfigureLogging((hostingContext, logging) =>
                    {
                        //logging.AddNLog(); //<--- Can remove (NLog.Extensions.Logging)
                    })
                    ;
            })
            .UseNLog(); // <--- Call UseNLog off of IHostBuilder (NLog.Web)
}

see https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3

When you debug, does User.Identity.Name resolve to anything?调试时, User.Identity.Name解析为任何内容?

I ran into this and fixed it by adding a claim with ClaimTypes.Name to the ClaimsPrincipal.我遇到了这个问题并通过向ClaimTypes.Name添加一个带有ClaimTypes.Name来修复它。 I had all the claims I needed, but ClaimsIdentity was looking for a specific claim to generate the name.我拥有所需的所有声明,但ClaimsIdentity正在寻找特定声明来生成名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 文件名中的aspnet-user-identity,但它并不总是有效 - aspnet-user-identity in filename, but it doesn't always work AspNet 核心标识 GetExternalLoginInfoAsync 始终为空 - AspNet Core Identity GetExternalLoginInfoAsync Always Null NLog 5.0 与 .net Framework 4.7.2 - aspnet 请求渲染器为空 - NLog 5.0 with .net Framework 4.7.2 - aspnet request renderers are empty User.Identity.GetUserId() 在 .net Core 中总是返回 null - User.Identity.GetUserId() always returns null in .net Core .Net 核心 API Microsoft.AspNet.Identity.Core - .Net Core API Microsoft.AspNet.Identity.Core 如何在带有 AspNet Core Identity 的 .net core 5.0 中使用 keycloak? - How to use keycloak in .net core 5.0 with AspNet Core Identity? Aspnet Core 身份管理总是让我返回登录页面 - Aspnet Core Identity management always returning me to the login page AspNet Core 5.0 并注册自定义 NLog LayoutRenderer - AspNet Core 5.0 and register custom NLog LayoutRenderer 当用户 ID 类型从字符串更改为 integer 时,User.Identity.IsAuthenticated 在 .net 核心中始终为假 - User.Identity.IsAuthenticated always false in .net core when user id type changed from string to integer .NET 核心 Web API HttpContext.User.Claims 和 HttpContext.User.Identity 在控制器中总是 null - .NET Core Web API HttpContext.User.Claims and HttpContext.User.Identity are always null in Controllers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM