How to get user information in DbContext using Net Core

I implemented an approach similar to this that is covered in this blog post and basically involves creating a service that will use dependency injection to inject the HttpContext (and underlying user information) into a particular context, or however you would prefer to use it.

A very basic implementation might look something like this:

public class UserResolverService  
{
    private readonly IHttpContextAccessor _context;
    public UserResolverService(IHttpContextAccessor context)
    {
        _context = context;
    }

    public string GetUser()
    {
       return _context.HttpContext.User?.Identity?.Name;
    }
}

You would just need to inject this into the pipeline within the ConfigureServices method in your Startup.cs file :

services.AddTransient<UserResolverService>();

And then finally, just access it within the constructor of your specified DbContext :

public partial class ExampleContext : IExampleContext
{
    private YourContext _context;
    private string _user;
    public ExampleContext(YourContext context, UserResolverService userService)
    {
        _context = context;
        _user = userService.GetUser();
    }
}

Then you should be able to use _user to reference the current user within your context. This can easily be extended to store / access any content available within the current request as well.

Leave a Comment