Sample code for how to use Session in ASP. NET Core

  • 2021-11-29 06:37:10
  • OfStack

ASP. NET Core is a cross-platform, open source, lightweight, high-performance and highly modular web framework. Session can store user information and track users between multiple requests from the same client. Microsoft. AspNetCore. Session middleware can be used in ASP. Net Core to enable Session mechanism.

The value of middleware is that it can be used in request- > In the process of response, do some customized operations, such as monitoring data, switching routes, modifying the message body in the process of flow. Generally speaking, middleware is poured into ASP. Net Core pipeline pipeline in a chain way. This article mainly discusses how to use Session middleware.

Installing Session middleware

To use the session middleware, you can install it using the NuGet package manager visual interface in Visual Studio 2019, or enter the following command from the NuGet package manager console command line:


Install-Package Microsoft.AspNetCore.Session

Configuring session middleware

Now that Microsoft. AspNetCore. Session has been successfully installed in your project, you can add it to ASP. Net, Core, pipeline, please note that in order to start Session, you must use an cache store that implements the IDistributedCache interface as the underlying storage of session, then you have to call AddSession method on ConfigureServices method to plug it into IOC container, and finally use UseSession under Startup. request method to plug it into request- > In the response request pipeline, the specific code is as follows:


  public void ConfigureServices(IServiceCollection services)
  {
    services.AddDistributedMemoryCache();
    services.AddSession(options =>
    {
      options.IdleTimeout = TimeSpan.FromSeconds(5);
      options.Cookie.HttpOnly = true;
      options.Cookie.IsEssential = true;
    });
    services.AddMvc()
      .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  }

1 Once the session middleware is added to the IOC container, UseSession can be called in the Configure method to start session.


  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSession();
    app.UseHttpContextItemsMiddleware();
    app.UseMvc();
  }

Storing and retrieving session

You can use Set, SetInt32 and SetString to store Session. These methods have two parameters, one is the key, one is the data corresponding to the key, and value of Set method corresponds to byte [].

Similarly, you can use the Get, GetInt32, and GetString methods to read session, while the Get method receives an key in string format and returns an byte [] array. To use these extension methods, you need to reference Microsoft. AspNetCore. Http to the project.

The following code shows how to add data to session.


public IActionResult Index()
{
  HttpContext.Session.SetString("Message", "Hello World!");
  HttpContext.Session.SetInt32("Year", 2019);
  return View();
}

Next, let's look at how to get data from session, as shown in the following code:


public IActionResult About()
{
  ViewBag.Message = HttpContext.Session.GetString("Message");
  ViewBag.Year = HttpContext.Session.GetInt32("Year");
  return View();
}

If you want to set or get data belonging to other types, you can add an extension method on the ISession interface and implement serialization logic by yourself. When setting or getting complex types from session, you can serialize this type into json, or deserialize json into model.

One more point to note is that the default session is memory-based, which means that session will be lost when the process is shut down. If you want to realize session persistence, you can use sqlserver or redis.

Translation link: https://www.infoworld.com/article/3411563/how-to-work-session-state-in-aspnet-core-html


Related articles: