6

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?

Chris.ZA
  • 1,218
  • 1
  • 15
  • 30
Zeus82
  • 6,065
  • 9
  • 53
  • 77
  • probably you can create an **abstract class** with **userId property** for all events and commands, have `IHttpContextAccessor` in it and assign the **userId**. Your question doesn't have any sample code or context, so we couldn't help much. – Kien Chu Oct 23 '18 at 02:42

1 Answers1

14

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.

Chris.ZA
  • 1,218
  • 1
  • 15
  • 30