Get Current User Outside an ASP.NET Controller

bojanv91

Bojan Veljanovski

Posted on January 3, 2021

Get Current User Outside an ASP.NET Controller

You can access the currently authenticated user from a controller action method in the following way:

[Route("[controller]")]
public class InternalController : ControllerBase
{
  [HttpGet]
  [Authorize]
  public string GetCurrentUser()
  {
    return base.User.Identity.Name;
  }
}
Enter fullscreen mode Exit fullscreen mode

To access it outside the controller, for example in a MediatR handler, you need to inject and use the IHttpContextAccessor service, which is already provided by ASP.NET:

[Route("[controller]")]
public class InternalController : ControllerBase
{
  private readonly IMediator _mediator;

  public InternalController(IMediator mediator) 
  {
    _mediator = mediator;
  }

  [HttpGet]
  [Authorize]
  public async Task<string> GetCurrentUser()
  {
    var response = await _mediator.Send(new GetCurrentUser.Request());
    return response.CurrentUserName;
  }
}

public class GetCurrentUser
{
  public class Request : IRequest<Response> { }

  public class Response 
  { 
    public string CurrentUserName { get; set; }
  }

  public class Handler : IRequestHandler<Request, Response>
  {
    private readonly IHttpContextAccessor _httpContextAccessor;

    public Handler(IHttpContextAccessor httpContextAccessor)
    {
      _httpContextAccessor = httpContextAccessor;
    }

    public Task<Response> Handle(Request request, CancellationToken cancellationToken)
    {
      return Task.FromResult(new Response 
      { 
        CurrentUserName = _httpContextAccessor.HttpContext.User.Name
      });
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Finally, to make this work, you need to register the IHttpContextAccessor dependency in your Startup class:

// ConfigureServices
services.AddHttpContextAccessor();
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
bojanv91
Bojan Veljanovski

Posted on January 3, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related