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.
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.
- using HttpContextProject.Helpers;
- using HttpContextProject.Models;
- using Microsoft.AspNetCore.Mvc;
- using System.Diagnostics;
- namespace HttpContextProject.Controllers
- {
- public class HomeController : Controller
- {
- public IActionResult Index()
- {
- return View();
- }
- public IActionResult About()
- {
- // handle the request and do something
- var requestHandler = new RequestHandler();
- requestHandler.HandleAboutRequest();
- ViewData["Message"] = "This is our default message for About Page!";
- return View();
- }
- }
- }
- namespace HttpContextProject.Helpers
- {
- public class RequestHandler
- {
- internal void HandleAboutRequest()
- {
- // do something here
- }
- }
- }
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,
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,
- using HttpContextProject.Helpers;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- namespace HttpContextProject
- {
- public class Startup
- {
- public IConfiguration Configuration { get; }
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- public void ConfigureServices(IServiceCollection services)
- {
- services.Configure<CookiePolicyOptions>(options => {
- options.CheckConsentNeeded = context => true;
- options.MinimumSameSitePolicy = SameSiteMode.None;
- });
- services.AddSession();
- services.AddSingleton<RequestHandler>();
- services.AddHttpContextAccessor();
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
- }
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment()) {
- app.UseDeveloperExceptionPage();
- }
- else {
- app.UseExceptionHandler("/Home/Error");
- }
- app.UseSession();
- app.UseMvc(routes => {
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
- });
- }
- }
- }

thiru aPosted Jun 12, 2021, 4:45 PM
Why static? Im afraid it is going to hold same HttpContextAccessor object throughout the app lifetime. I prefer your previous post which the request specific as the HttpContext has to be request specific..
Iván KollárPosted Dec 18, 2020, 4:58 AM
Nice, thanks!
Ajay PattniPosted Jun 17, 2019, 10:31 AM
How can i access this call in view model
Farhan AhmedPosted Jul 24, 2018, 3:34 AM
Nice article
Vikas SrivastavaPosted Jul 22, 2018, 1:48 PM
Awesome article....
Jeeva SubburajPosted Jul 21, 2018, 9:05 PM
Nice article about accessing session data outside controller using dependency injection.. thanks
Abhishek MishraPosted Jul 21, 2018, 3:31 AM
This is useful.
Hadshana KamalanathanPosted Jul 20, 2018, 10:38 AM
Good sharing..