Saturday, July 11, 2015

ASP.NET Core / MVC 6 HttpContext.Current

As you know with MVC 6, HttpContext is rewritten and one of the most used functionality , HttpContext.Current is dropped. In most situations you don’t need this and you should use Controller context. But in some situations you may need access to HttpContext. In my scenario I want to pass some data using HttpContext.Items from one layer (middleware) to another (business layer).

Below are the two ways to get current HttpContext:

  • Using dependency injection we can inject the HttpContext on to the service directly. DI injects a singleton object called HttpContextAccessor which is used to retrieve the current HttpContext. Here is the sample code for this

    public class MyService
    {
        private HttpContext context;
        public MySerivce(IHttpContextAccessor contextAccessor)
        {
            this.context = contextAccessor.HttpContext;
        }

  •  Similar to HttpContext.Current we can also create a static class that holds the reference for the current HttpContext. Here is the code for this static class

    public static class HttpHelper
    {
        private static IHttpContextAccessor HttpContextAccessor;
        public static void Configure(IHttpContextAccessor httpContextAccessor)
        {
            HttpContextAccessor = httpContextAccessor;
        }

        public static HttpContext HttpContext
        {
            get
            {
                return HttpContextAccessor.HttpContext;
            }
        }
    }

This static HttpHelper class stores the singleton HttpContextAccessor and is then used to return the current HttpContext. We will configure our HttpHelper in our startup as shown below

        public void Configure(IApplicationBuilder app)
        {
            //other code
            HttpHelper.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
        }

Finally we can get current HttpContext wherever we need using our Helper as below
HttpHelper.HttpContext

As you see using the above two approaches to get the current HttpContext.

Please see my updated post on this. I am using CallContext to pass the HttpContext and other data
ASP.NET Core Async Context Data