Get Current User Outside an ASP.NET Controller
Bojan Veljanovski
Posted on January 3, 2021
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;
}
}
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
});
}
}
}
Finally, to make this work, you need to register the IHttpContextAccessor
dependency in your Startup
class:
// ConfigureServices
services.AddHttpContextAccessor();
💖 💪 🙅 🚩
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
linux Steps to Use .NET on the Forlinx OKMX6UL Series Development Board (Linux4.1.15)
November 29, 2024
opentelemetry Observing Spin Apps with OpenTelemetry and the .NET Aspire Dashboard
November 27, 2024