web analytics

Using Sessions and HttpContext in ASP.NET Core

Options

codeling 1602 - 6666
@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.AddMvc();
services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
services.AddSession();

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

// IMPORTANT: This session call MUST go before UseMvc()
app.UseSession();

@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 demonstrates 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");
    }
}

 

The above approach needs you to register a dependency using the built-in dependency injection container. The dependency injection container supplies the IHttpContextAccessor to any classes that declare it as a dependency in their constructors:

public void ConfigureServices(IServiceCollection services)
{
     services.AddControllersWithViews();
     services.AddHttpContextAccessor();
     .....
}

@2021-10-24 21:24:11

Use HttpContext from middleware

When working with custom middleware components, HttpContext is passed into the Invoke or InvokeAsync method and can be accessed when the middleware is configured:

public class MyCustomMiddleware
{
    public Task InvokeAsync(HttpContext context)
    {
        ...
    }
}

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com