简体   繁体   English

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

[英]Get username within startup.cs in Asp.net core

I'm using Asp.net Core Authorization and I need to get username within startup.cs but I got null. 我正在使用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));
}

I found the problem why httpContext.User.Identity.Name is always empty. 我发现了为什么httpContext.User.Identity.Name始终为空的问题。 for each request to server the header should have Authorization header like below: 对于服务器的每个请求,标头都应具有Authorization标头,如下所示:

Key                Value
Authorization      Bearer ZQ0QZFANcPogvA...

without Bearer httpContext is always null. 没有Bearer的httpContext始终为null。 not bad to visit this link 可以访问此链接

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM