DEV Community

codingpipe
codingpipe

Posted on

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

Top comments (1)

Collapse
 
kharel_tapan profile image
Tapan

In this example just we get the current user email or name, but how we can get the full user details,