我正在使用 Asp.net Core 授权,我需要在 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 都应该有 Authorization header ,如下所示:
Key Value
Authorization Bearer ZQ0QZFANcPogvA...
没有 Bearer httpContext 总是空的。不错的访问这个link
关于c# - 在 Asp.net Core 的 startup.cs 中获取用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53395425/