web analytics

Using Sessions and HttpContext in ASP.NET MVC Core


codeling 1524 - 6369
@2021-05-21 23:28:50

Add sessions to the ASP.NET Core pipeline

Open up startup.cs and add the AddSession() call to the ConfigureServices(IServiceCollection services)

// Add MVC services to the services container.
services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache

Next add the UseSession() call below to the Configure(IApplicationBulider app, ...)

// IMPORTANT: This session call MUST go before UseMvc()

@2021-05-21 23:35:21

Use sessions in a controller

You can now find the session object by using HttpContext.Session. HttpContext is just the current HttpContext exposed to you by the Controller class.

The following example shows how to use sessions in the Home Controller:

using Microsoft.AspNetCore.Http; // Needed for the SetString and GetString extension methods

public class HomeController : Controller
    public IActionResult Index()
        HttpContext.Session.SetString("Test", "Ben Rules!");
        return View();

    public IActionResult About()
        ViewBag.Message = HttpContext.Session.GetString("Test");

        return View();

@2021-05-22 10:17:44

Inject the context into a random class

If you’re not in a controller, you can still access the HttpContext by injecting IHttpContextAccessor.

The following example demostrates how to inject the context into a random class:

public class SomeOtherClass
    private readonly IHttpContextAccessor _httpContextAccessor;

    public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
        _httpContextAccessor = httpContextAccessor;

    public void TestSet()
        _httpContextAccessor.HttpContext.Session.SetString("Test", "Ben Rules!");

    public void TestGet()
        var message = _httpContextAccessor.HttpContext.Session.GetString("Test");


You must Sign In to comment on this topic.

© 2021 Digcode.com