在 Asp.net 核心中获取 startup.cs 内的用户名

Get username within startup.cs in Asp.net core

我正在使用 Asp.net 核心授权,我需要在 startup.cs 内获取用户名,但我得到的是空值。

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));
}

我发现了为什么 httpContext.User.Identity.Name 总是空的问题。对于每个对服务器的请求,header 应该有 A​​uthorization header,如下所示:

Key                Value
Authorization      Bearer ZQ0QZFANcPogvA...

没有 Bearer httpContext 总是空的。不错,可以参观这个link