Get username within startup.cs in Asp.net core

1.3k Views Asked by At

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));
}
1

There are 1 best solutions below

1
On BEST ANSWER

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:

Key                Value
Authorization      Bearer ZQ0QZFANcPogvA...

without Bearer httpContext is always null. not bad to visit this link