I'm using Asp.net Core Authorization and I need to get username within startup.cs but I got 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. for each request to server the header should have Authorization header like below:
without Bearer httpContext is always null. not bad to visit this link