在Asp.net Core中的startup.cs中获取用户名

时间:2018-11-20 14:39:37

标签: c# asp.net-core audit.net

我正在使用Asp.net Core授权,我需要在startup.cs中获取用户名,但我得到的是null。

public void ConfigureServices(IServiceCollection services)
{        
    // some code here
    services.AddHttpContextAccessor();
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddHttpContextAccessor();
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            Audit.Core.Configuration.Setup()
                .UseEntityFramework(_ => _
                    .AuditTypeMapper(t => typeof(AuditLog))
                    .AuditEntityAction<AuditLog>((ev, entry, entity) =>
                    {
                        var svcProvider = services.BuildServiceProvider();
                        var httpContext = svcProvider.GetService<IHttpContextAccessor>().HttpContext;

                        entity.AuditData = JsonConvert.SerializeObject(entry);
                        entity.EntityType = entry.EntityType.Name;
                        entity.AuditDate = DateTime.Now;
                        entity.AuditUser = httpContext.User.Identity.Name;
                    })
                .IgnoreMatchedProperties(true));
}

1 个答案:

答案 0 :(得分:0)

我发现了为什么httpContext.User.Identity.Name始终为空的问题。对于每个服务器请求,标头应具有 Authorization 标头,如下所示:

low ,medium, high

无承载httpContext始终为null。可以访问此link