Search code examples
c#mediatrasp.net-core-2.2

MediatR - Handling current user in query


What is the best way to model the current user in a query? I'm creating a razor page application. I need to be able to attach the current user when I am executing queries and commands. Is there a recommended approach for doing this?


Solution

  • The below approach works well for me as I have the get the user into a service layer that my Razor projects depend on.

    As per the guidance by David Fowler here, I created a UserAccessor class as follows:

    public interface IUserAccessor { ClaimsPrincipal User { get; } }
    
    public class UserAccessor : IUserAccessor
    {
        private readonly IHttpContextAccessor _accessor;
    
        public UserAccessor(IHttpContextAccessor accessor)
        {
            _accessor = accessor ?? throw new ArgumentNullException(nameof(accessor));
        }
    
        public ClaimsPrincipal User => _accessor.HttpContext.User;
    }
    

    which I register in my Razor project on startup by calling

    services.AddTransient<IUserAccessor, UserAccessor>()
    

    and then inject that into the MediatR handlers and my DbContext as well as some factories as required.

    private readonly IUserAccessor _userAccessor;
    
    public EventLogFactory(IUserAccessor userAccessor)
    {
        _userAccessor = userAccessor ?? throw new ArgumentNullException(nameof(userAccessor));
    } 
    

    The IHttpContextAccessor referenced in UserAccessor requires the Microsoft.AspNetCore.Http.Abstractions nuget in projects that don't reference Microsoft.AspNetCore.App meta package and will also require that your Razor project implements AddHttpContextAccessor()on startup as well:

    // Register IHttpContextAccessor for services to get access to the HttpContext.  
    services.AddHttpContextAccessor();
    

    Hope this helps.