I have a scenario where I need to access User.Identity
Claims in my Constructor's Controller.
I need this because the Claims have information required for me to spin up a custom DB Context (Connection String)
How can I go about accessing this? I would just inject in the DBContext, but based on the user, they may need to access a different DB.
Is there a better way to think about this?
[Authorize]
public class DefaultController : Controller
{
public DefaultController()
{
// this is NULL
var authenticatedUser = User.Identity.Name;
}
}
As of version 2.1 of ASP.NET Core, HttpContextAccessor
is provided. For this we must follow the following steps:
Configure the service using the standard implementation in the ConfigureServices
method of Startup.cs
:
services.AddHttpContextAccessor();
Perform the dependency injection of IHttpContextAccessor
on the controllers. Use HttpContext
property for access to User
[Authorize]
public class DefaultController : Controller
{
public DefaultController(IHttpContextAccessor contextAccessor)
{
// Here HttpContext is not Null :)
var authenticatedUser = contextAccessor.HttpContext.User.Identity.Name;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With