![](/img/trans.png)
[英]Get Current URL as soon as available program.cs / startup.cs in ASP.NET Core
[英]Get username within startup.cs in Asp.net core
我正在使用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));
}
我发现了为什么httpContext.User.Identity.Name始终为空的问题。 对于服务器的每个请求,标头都应具有Authorization标头,如下所示:
Key Value
Authorization Bearer ZQ0QZFANcPogvA...
没有Bearer的httpContext始终为null。 可以访问此链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.