Using HttpContext Outside An MVC Controller In .Net Core 2.1

With .Net Core 2.1 we can not access the HttpContext outside a controller, however, we can use the IHttpContextAccessor to access the current session outside a controller.

Introduction

Last Friday, while working on a web application based on ASP.Net Core 2.1, I came across a scenario where I had to put some data into memory. While that's not a problem, the catch is that the data has to be unique for each HTTP Session. Consider it as keeping a key that is to be used across different views to display some information related to that particular session.

The only possible solution satisfying my needs was to keep the "key" in session. However, the last point in the code that has access to the key is a simple helper class and not an MVC Controller. And we had no intentions to expose the "key" to our controller. So, the question remains: how do we save the key in session without exposing it to the controller? 

Sample Code

In the following code, we have a very basic MVC application with our HomeController. We also have a RequestHandler that takes care of all the background logic making our controller clean and light. 
  1. using HttpContextProject.Helpers;  
  2. using HttpContextProject.Models;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using System.Diagnostics;  
  5.   
  6. namespace HttpContextProject.Controllers  
  7. {  
  8.     public class HomeController : Controller  
  9.     {  
  10.         public IActionResult Index()  
  11.         {  
  12.             return View();  
  13.         }  
  14.   
  15.         public IActionResult About()  
  16.         {  
  17.             // handle the request and do something  
  18.             var requestHandler = new RequestHandler();  
  19.             requestHandler.HandleAboutRequest();  
  20.   
  21.             ViewData["Message"] = "This is our default message for About Page!";  
  22.             return View();  
  23.         }  
  24.     }  
  25. }  
  26.   
  27.   
  28. namespace HttpContextProject.Helpers  
  29. {  
  30.     public class RequestHandler  
  31.     {  
  32.         internal void HandleAboutRequest()  
  33.         {  
  34.             // do something here  
  35.         }  
  36.     }  
  37. }  
As it can be seen in the above code, we are simply setting a message in the ViewData and rendering it on the view. Nothing fancy so far. Now, let's see how we can set our message in Http Session from RequestHandler and later access it inside the controller.

Using HttpContext in a Helper Class 

With .Net Core 2.1 we can not access the HttpContext outside a controller, however, we can use the IHttpContextAccessor to access the current session outside a controller. In order to do so, we need to add the Session and HttpContextAccessor middle-ware to ConfigureServices method of our Startup class as shown in the code below,
  1. using HttpContextProject.Helpers;  
  2. using Microsoft.AspNetCore.Builder;  
  3. using Microsoft.AspNetCore.Hosting;  
  4. using Microsoft.AspNetCore.Http;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using Microsoft.Extensions.Configuration;  
  7. using Microsoft.Extensions.DependencyInjection;  
  8.   
  9. namespace HttpContextProject  
  10. {  
  11.     public class Startup  
  12.     {  
  13.         public IConfiguration Configuration { get; }  
  14.         public Startup(IConfiguration configuration)  
  15.         {  
  16.             Configuration = configuration;  
  17.         }         
  18.   
  19.         public void ConfigureServices(IServiceCollection services)  
  20.         {  
  21.             services.Configure<CookiePolicyOptions>(options => {  
  22.                 options.CheckConsentNeeded = context => true;  
  23.                 options.MinimumSameSitePolicy = SameSiteMode.None;  
  24.             });  
  25.             services.AddSession();  
  26.             services.AddSingleton<RequestHandler>();  
  27.             services.AddHttpContextAccessor();  
  28.             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  29.         }  
  30.   
  31.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  32.         {  
  33.             if (env.IsDevelopment()) {  
  34.                 app.UseDeveloperExceptionPage();  
  35.             }  
  36.             else {  
  37.                 app.UseExceptionHandler("/Home/Error");  
  38.             }  
  39.             app.UseSession();  
  40.             app.UseMvc(routes => {  
  41.                 routes.MapRoute(  
  42.                     name: "default",  
  43.                     template: "{controller=Home}/{action=Index}/{id?}");  
  44.             });  
  45.         }  
  46.     }  
  47. }  
The next thing we need to do is to add a dependency of IHttpContextAccessor in the RequestHandler. This allows us to access the HttpContext inside the request handler. After we have done required processing for the request, we can now set the message in session, using the Session.SetString(key, value) method. Please refer to the code below,
  1. using Microsoft.AspNetCore.Http;  
  2.   
  3. namespace HttpContextProject.Helpers  
  4. {  
  5.     public class RequestHandler  
  6.     {  
  7.         IHttpContextAccessor _httpContextAccessor;  
  8.         public RequestHandler(IHttpContextAccessor httpContextAccessor)  
  9.         {  
  10.             _httpContextAccessor = httpContextAccessor;  
  11.         }  
  12.   
  13.         internal void HandleAboutRequest()  
  14.         {  
  15.             // handle the request  
  16.             var message = "The HttpContextAccessor seems to be working!!";  
  17.             _httpContextAccessor.HttpContext.Session.SetString("message", message);  
  18.         }  
  19.     }  
  20. }  
Now, that we have our RequestHandler all set, it's time to make some changes in the HomeController. Currently, the "new" RequestHandler  is inside the action method, which is not a good practice. So, I will decouple the handler from the controller and rather inject it as a dependency in the constructor. Next thing we do is to set the message in ViewData from the session, as shown in the code below,
  1. using HttpContextProject.Helpers;  
  2. using HttpContextProject.Models;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using System.Diagnostics;  
  5.   
  6. namespace HttpContextProject.Controllers  
  7. {  
  8.     public class HomeController : Controller  
  9.     {  
  10.         private readonly RequestHandler _requestHandler;  
  11.   
  12.         public HomeController(RequestHandler requestHandler)  
  13.         {  
  14.             _requestHandler = requestHandler;  
  15.         }  
  16.   
  17.         public IActionResult About()  
  18.         {  
  19.             _requestHandler.HandleAboutRequest();  
  20.             ViewData["Message"] = HttpContext.Session.GetStringValue("message");  
  21.             return View();  
  22.         }  
  23.     }  
  24. }  
Note that I'm using Sesseion.GetStringValue(key) which is an extension method that I have added to retrieve data from the session, however, it's not really required. You can simply use the Session.TryGetValue(key, value) as well.

In case you have not figured it out already, I must tell you that we need to register our RequestHandler in the ConfigureServices method of the Startup class so that the dependency for our controller can be resolved.

Summary

With the above changes in place, we can now access the HttpContext.Session inside our request handler and the same can be done for any other class as well. However, there is one thing that I don't like about this approach. For every single component where we need to access the session, we have to inject a dependency of IHttpContextAccessor.

While for one or two components it's not a problem, it can be very daunting if we have to do the same over and over again. There is a way to achieve the same accessibility without having to inject any dependency, but that's a story for another day and I will write about that in my next post.

Update

Checkout my latest article discussing a better approach to access HttpContext outside a Controller in .Net Core 2.1

Related Articles