ASP.NET Core Access User.Identity in Controller Constructor

asp.net-core asp.net-core-mvc c# entity-framework-core

Question

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;
    }
}
1
9
6/28/2018 12:29:55 AM

Popular Answer

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;
    }
}
18
8/18/2018 6:21:17 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow