10

I am trying to figure out how to get access to the current logged in username outside of an ASP.NET Controller.

For example I am trying to do this:

Track Created and Modified fields Automatically with Entity Framework Code First

To setup tracking on entities in the DbContext.

Here is my ApplicationDbContext but I keep getting an error saying _httpContextAccessor is null:

private readonly IHttpContextAccessor _httpContextAccessor;

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor httpContextAccessor)
    : base(options)
{
    _httpContextAccessor = httpContextAccessor;
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Blake Rivell
  • 13,105
  • 31
  • 115
  • 231
  • See https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context there is a `AddHttpContextAccessor` extension method. – Fred Nov 21 '19 at 14:27

2 Answers2

13

Try injecting the IHttpContextAccessor Interface

You can even abstract it further by creating a service to provide just the information you want (Which is the current logged in username)

public interface IUserResolverService {
    string GetUser();
}

public class UserResolverService : IUserResolverService {
    private readonly IHttpContextAccessor accessor;
    public UserResolverService(IHttpContextAccessor accessor) {
        this.accessor = accessor;
    }

    public string GetUser() {
        var username = accessor?.HttpContext?.User?.Identity?.Name ;
        return username ?? "unknown";
    }
}

You need to setup IHttpContextAccessor now in Startup.ConfigureServices in order to be able to inject it:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//OR
//services.AddHttpContextAccessor();
services.AddTransient<IUserResolverService, UserResolverService>();

and pass that to your repository as needed to record associated username

Nkosi
  • 235,767
  • 35
  • 427
  • 472
6

@Nkosi has the correct answer but please note that IHttpContextAccessor is now under the namespace:

Microsoft.AspNetCore.Http;

And no longer under:

Microsoft.AspNet.Http;
Stephen Brickner
  • 2,584
  • 1
  • 11
  • 19