Take advantage of the session middleware component in ASP.Net Core to store and retrieve user data Credit: Matejmo / Getty Images ASP.Net Core is an open source, cross-platform, lean, extensible and modular framework for building high-performance web applications. Session state in ASP.Net Core enables you to store user data and persist the data across requests from the same client. You can take advantage of the necessary middleware (available as part of the (Microsoft.AspNetCore.Session package) to work with session state in ASP.Net Core. Middleware components in ASP.Net Core are used to customize the handling of requests and responses, and inspect, route, or modify the request and response messages that flow through the pipeline. Usually, you have a chain of middleware components in the application pipeline in ASP.Net Core. This article presents a discussion on how we can work with session state in ASP.Net Core. Create an ASP.Net Core MVC project First off, let’s create an ASP.Net Core project in Visual Studio. Assuming Visual Studio 2017 or Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.Net Core project in Visual Studio. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.Net Core Web Application” from the list of templates displayed. Click Next. In the “Configure your new project” window shown next, specify the name and location for the new project. Click Create. In the “Create New ASP.Net Core Web Application” shown next, select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top. Select “Web Application (Model-View-Controller)” as the project template to create a new ASP.NET Core application. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set to “No Authentication” as we won’t be using authentication either. Click Create. You should now have a new ASP.NET Core project ready to go in Visual Studio. We’ll use this project in the subsequent sections of this article to work with session state. Install the ASP.Net Core session state middleware The next step is to install the necessary NuGet package for working with session state. The NuGet package we need is Microsoft.AspNetCore.Session. To add the Microsoft.AspNetCore.Session NuGet package to your project, right-click on the project in the Solution Explorer window, and click on “Manage NuGet Packages…” Then search for this package in the NuGet Package Manager and install it. Alternatively, you can install this package from the NuGet Package Manager Console using the following command: PM> Install-Package Microsoft.AspNetCore.Session Configure the ASP.Net Core session state middleware Now that the necessary NuGet package has been installed on your project, you can add the session middleware component to the ASP.Net Core pipeline. Note that to enable session state in ASP.Net Core you must add any of the IDistributedCache memory caches you want to use as a backing storage for session. You must also make a call to AddSession in the ConfigureServices method to add the session middleware to the ASP.Net Core pipeline. Lastly, you must make a call to the UseSession method in the Configure method of the Startup class. The following code snippet shows how you can add the session middleware to the ASP.Net Core pipeline in the ConfigureServices method. 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); } Once the session middleware component has been added to the pipeline, you must make a call to the UseSession method in the Configure method of the Startup class. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSession(); app.UseHttpContextItemsMiddleware(); app.UseMvc(); } Store and retrieve data to and from a session in ASP.Net Core You can take advantage of the methods Set, SetInt32, and SetString to set session values. These methods accept a key and the data to be stored as arguments. The Set method accepts a byte array as an argument. Similarly, you have the Get, GetInt32, and GetString methods to retrieve data from the session based on a key. The Get method accepts a key as an argument and returns a byte array. To use these methods you should add a reference to Microsoft.AspNetCore.Http in your code. The following code snippet illustrates how you can add data to the session in your controller’s action method. public IActionResult Index() { HttpContext.Session.SetString("Message", "Hello World!"); HttpContext.Session.SetInt32("Year", 2019); return View(); } And here is how you can retrieve those values in your controller’s action method. public IActionResult About() { ViewBag.Message = HttpContext.Session.GetString("Message"); ViewBag.Year = HttpContext.Session.GetInt32("Year"); return View(); } If you would like to set or get data pertaining to other types, you should create your own extension methods on ISession and implement the necessary serialization logic yourself. To store and retrieve a complex object to and from the session, you can serialize and deserialize the object to JSON. Instead of using the in-memory cache you can also store session data in SQL Server or Redis. Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos