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

问题描述 投票:1回答:1

我正在使用Asp.net核心授权,我需要在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));
}
c# asp.net-core audit.net
1个回答
0
投票

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

Key                Value
Authorization      Bearer ZQ0QZFANcPogvA...

没有Bearer的httpContext始终为null。参观这个link也不错

© www.soinside.com 2019 - 2024. All rights reserved.