Take advantage of session storage middleware in ASP.Net Core to store user-specific data and session state on the server Credit: Gerd Altmann To store user-specific data in ASP.Net Core web applications, we use the session state. However, using session state in ASP.Net core is not straightforward—at least, session state in ASP.Net Core doesn’t work the way it used to work in legacy ASP.Net applications. This article examines how we can work with session state in ASP.Net Core. Create an ASP.Net Core Web API project First off, let’s create an ASP.Net Core project and install the necessary packages. If Visual Studio 2017 is up and running in your system, follow the steps outlined below to create an ASP.Net Core Web API project. Launch the Visual Studio 2017 IDE. Click on File > New > Project. Select “ASP.Net Core Web Application (.Net Core)” from the list of templates displayed. Specify a name for the project. Click OK to save the project. Select “API” in the “New .Net Core Web Application…” window. Select “.Net Core” as the runtime and ASP.Net Core 2.1 (or later) from the drop-down list of controls at the top. Select “Web Application (Model-View-Controller)” as the project template. Uncheck the “Enable Docker Support” box. Ensure that “No Authentication” is selected as we won’t be using authentication here. Ensure that “Configure for HTTPS” is unchecked as we won’t need HTTPS either. (See the figure below.) Click OK. This will create a new ASP.Net Core 2.1 MVC project in Visual Studio 2017. IDG Creating a new ASP.Net Core MVC project in Visual Studio 2017. Install the ASP.Net Core session state middleware To get up and running with sessions, we must add the Microsoft.AspNetCore.Session NuGet package to our project. To do this, select the newly created project in the Solution Explorer window, then right-click and select the “Manage NuGet Packages…” option to open the NuGet Package Manager window. Next, search for the Microsoft.AspNetCore.Session NuGet package and install it. Configure the ASP.Net Core session state middleware The next step is to add the services for working with session state and configuring the HTTP request pipeline. Here is how you can add the services in the ConfigureServices method of the Startup.cs file. public void ConfigureServices(IServiceCollection services) { services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(1); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } Next, you can enable session state for the application in the Configure method of the Startup.cs file as shown in the code snippet below. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseSession(); app.UseMvc(); } And that’s it for configuration. In the section that follows, we will examine how we can use session state in the controller methods. Store and retrieve session data in ASP.Net Core User session data is stored in key-value pairs. You can get the session object by using HttpContext.Session, where HttpContext represents the current context. You can use the HttpContext.Session.SetString() method to store a string and the HttpContext.Session.GetString() method to retrieve the string based on a key from the session. The following code snippet illustrates how these methods can be used. public class HomeController : Controller { public IActionResult Index() { HttpContext.Session.SetString(“Key”, “This is a test message.”); return View(); } public IActionResult About() { string message = HttpContext.Session.GetString(“Key”); ViewData[“Message”] = message; return View(); } } Check if session has expired in ASP.Net Core Note that we set the IdleTimeout for session storage to one minute in the ConfigureServices method of the Startup.cs file. So, after one minute of inactivity, the session data will be lost. We can update the code shown earlier to check if the session is still alive, i.e., that the session object is not null. Here is the updated code for the HomeController class for reference. public class HomeController : Controller { public IActionResult Index() { HttpContext.Session.SetString(“Key”, “This is a test message.”); return View(); } public IActionResult About() { string message = null; if (HttpContext.Session != null) { message = HttpContext.Session.GetString(“Key”); if(string.IsNullOrEmpty(message)) message =“Session timed out.”; } ViewData[“Message”] = message; return View(); } } Store complex objects in a session in ASP.Net Core If you want to store complex data in the session, you can create an extension class that serializes and de-serializes the objects appropriately as shown in the code snippet below. public static class SessionCoreExtensions { public static void Add<T>(this ISession iSession, string key, T data) { string serializedData = JsonConvert.SerializeObject(data); iSession.SetString(key, serializedData); } public static T Get<T>(this ISession iSession, string key) { var data = iSession.GetString(key); if(null != data) return JsonConvert.DeserializeObject<T>(data); return default(T); } } Assuming you have a POCO (plain old class object) called Author, you can store a complex object as shown in the code snippet below. var author = new Author(); HttpContext.Session.Add<author>(“Key”, author); To retrieve the complex object from the session, you can use the following code. var obj = HttpContext.Session.Get<Author>(“Key”); HTTP is a stateless protocol. Every request in the HTTP world occurs in absolute isolation. Whereas session state management was built into legacy ASP.Net, the leaner ASP.Net Core requires us to add the Microsoft.AspNetCore.Session middleware to support it. Albeit the fact that ASP.Net Core works a bit differently, storing session state is still easy to do when we need it. 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