In my previous article, we discussed an approach to access the HttpContext.Session in a RequestHandler outside our Homecontroller. However, there was a problem. For every single component where we need to access the session, we have to inject a dependency of IHttpContextAccessor. While it's not a problem for one or two components, it can be very daunting if we have to do the same over and over again. In this article, we will use a different approach to achieve the same.
The AppContextIn this approach, we are going to create a static AppContext class. This class is going to hold the current Http session as a property called Current. Previously, we used the IHttpContextAccessor to get the current Http session, likewise we are going to do that here. However, since I want to keep the AppContext static, we need a static method to inject IHttpContextAccessor to it, as shown in the code below,
- using Microsoft.AspNetCore.Http;
- namespace StaticHttpContextAccessor.Helpers
- {
- public static class AppContext
- {
- private static IHttpContextAccessor _httpContextAccessor;
- public static void Configure(IHttpContextAccessor httpContextAccessor)
- {
- _httpContextAccessor = httpContextAccessor;
- }
- public static HttpContext Current => _httpContextAccessor.HttpContext;
- }
- }
The Startup class in this case will be a little different from the previous one. We still need to add the IHttpContextAccessor to the ConfigureServices method. It is the ConfigureService method where we will inject the IHttpContextAccessor into the AppContext. And, to achieve that we are going to use the IApplicationBuilder as shown below,
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using StaticHttpContextAccessor.Helpers;
- namespace StaticHttpContextAccessor
- {
- public class Startup
- {
- public Startup(IConfiguration configuration) { Configuration = configuration; }
- public IConfiguration Configuration { get; }
- public void ConfigureServices(IServiceCollection services)
- {
- services.Configure<CookiePolicyOptions>(options => {
- options.CheckConsentNeeded = context => true;
- options.MinimumSameSitePolicy = SameSiteMode.None;
- });
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
- services.AddSession();
- services.AddHttpContextAccessor();
- services.AddSingleton<RequestHandler>();
- }
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
- else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); }
- app.UseHttpsRedirection();
- app.UseCookiePolicy();
- app.UseSession();
- AppContext.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
- });
- }
- }
- }
Just for fun, I added a few extension methods for ISession though it's not really required. But if you find them useful, go ahead to consume them in a real life project,
- using Microsoft.AspNetCore.Http;
- using Newtonsoft.Json;
- namespace StaticHttpContextAccessor.Helpers
- {
- public static class HttpSessionHelper
- {
- public static void Set<T>(this ISession session, string key, T value)
- {
- session.SetString(key, JsonConvert.SerializeObject(value));
- }
- public static T Get<T>(this ISession session, string key)
- {
- var value = session.GetString(key);
- return value == null ? default(T) :
- JsonConvert.DeserializeObject<T>(value);
- }
- }
- }
Now that we have the setup ready, it's time to set the message in our RequestHandler using the AppContext which gives us the current session. We can then get the mesage from the session in the controller, as we did in our previous approach. Please refer to the code below,
- namespace StaticHttpContextAccessor.Helpers
- {
- public class RequestHandler
- {
- public void HandleIndexRequest()
- {
- // do something for the request
- var message = "This is a much cleaner approach to access Session!";
- AppContext.Current.Session.Set<string>("message", message);
- }
- }
- }
- using Microsoft.AspNetCore.Mvc;
- using StaticHttpContextAccessor.Helpers;
- namespace StaticHttpContextAccessor.Controllers
- {
- public class HomeController : Controller
- {
- private readonly RequestHandler _requestHandler;
- public HomeController(RequestHandler requestHandler)
- {
- _requestHandler = requestHandler;
- }
- public IActionResult Index()
- {
- _requestHandler.HandleIndexRequest();
- ViewData["Message"] = HttpContext.Session.Get<string>("message");
- return View();
- }
- }
- }
If I compare this approach with the previous one, this one feels much cleaner. I would be more than happy to know what you guys think about the two. Which one would you choose and why? Please do let me know in the comments below.
If you have not read my previous article discussing the first approach, you can find the same at: Using HttpContext Outside An MVC Controller In .Net Core 2.1

Tahir AnsariPosted Apr 1, 2023, 6:43 AM
How to implement in dotnet 6
Kevin CrespoPosted Nov 10, 2021, 11:10 PM
Good afternoon, excellent example. Could you tell me or suggest a reference where it is related to the database or more complete, what I do not understand is how I keep the session started even if the user leaves the page and how I close the session manually and automatically based on a limit of time, thanks and regards.
Lam GiangPosted Sep 8, 2021, 2:05 AM
This is a very helpful article. It saves me !
Deven KoliPosted Sep 30, 2020, 7:00 AM
This was helpful, Thanks : )
Harkirat SinghPosted Jul 24, 2019, 8:22 AM
Ok I want to access it in a class within which i can't add constructor injection because that class is being exported to third party.How can i access session then in asp.net core?
Keyvan SadralodabaiPosted May 22, 2019, 6:11 PM
For me, it runs ConfigureServices before Configure, hence it's not set up when accessed.
Abinash PandaPosted Apr 26, 2019, 12:39 AM
How can we implement the same for Asp.net mvc 5
GrasseelsPosted Jan 23, 2019, 1:39 AM
Hello, i have a question, why use a AppContext class with static and don't use directly IHttpContextAccessor in DI ?
Marwa BalhoudiPosted Jan 4, 2019, 6:54 AM
Very helpful blog, thank you