How can we register IHttpContextAccessor in startup class in asp.net 2.1 core application? RRS feed

  • Question

  • User-303331888 posted

    We have an application in which User.Identity.Name is null for only one user. I have declared IHttpContextAccessor as static like below.

    public static IHttpContextAccessor HttpContextAccessor;

    I found something in the internet. Asp.net core will allow concurrent request at a time. If we declare IHttpContextAccessor as static, it will valid for first request alone. Please refer the link.

    As per the above reference, i have changed IHttpContextAccessor declaration from static to readonly. Also i changed the class where this IHttpContextAccessor declared, was changed from static to non static. So i have created object to access the class members in the places where we are accessing that class members.

    But in startup class, i could see the below code in configure method. Since i have declared IHttpContextAccessor as readonly, it giving below compile error for the below code.

    getScopedServices.HttpContextAccessor = services.GetService<IHttpContextAccessor>();

    Error screenshot

    What is the use of above code? i have already registered IHttpContextAccessor as singleton in Configure Services section like below. Do we really require the above code?

     #region Singleton
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            #endregion Singleton

    what will happen if we remove the below line from the code? Please help me on this.

    getScopedServices.HttpContextAccessor = services.GetService<IHttpContextAccessor>();
    Wednesday, September 9, 2020 1:04 PM

All replies

  • User-474980206 posted

    You can use a static for the HttpContextAccessor. You also only need to register it if you write a service that needs it injected. The httpcontext is already passed to a controller.

    explain what issue you are trying to solve with a static httpcontext? If you are porting code from web forms, that accessed HttpContext.Current, you need to modify the code to use a passed in HttpContext either for each method that requires it or in the constructor. There is no way to implement the equivalent to HttpContext.Current in asp.net core.


    Wednesday, September 9, 2020 2:33 PM