Search code examples
c#asp.net-mvcasp.net-core-mvcasp.net-identity

How to get current user's data in Controller's constructor?


I need to use some current user's data in controller's constructor to initialize repositories, but looks like impossible to get current user's data, because all objects, which can give any data about the user (for example HttpContext or User) is nullable in constructor's area. How can I get needed data inside the constructor or any other way initialize repositories with user's data?


Solution

  • You can use IHttpContextAccessor to access HttpContext in constructor;

    public class HomeController : Controller
    {
        public HomeController(IHttpContextAccessor httpContextAccessor)
        {
            var httpContext = httpContextAccessor.HttpContext;
        }
    }
    

    If you are using ASP.NET Core 1.x register IHttpContextAccessor in configure method in startup class and for ASP.NET Core 2.0 I think it is not required.

    services.TryAddScoped<IHttpContextAccessor, HttpContextAccessor>();