Problem
How to store data in session state using ASP.NET Core.
Solution
Using an empty project from a previous post, amend Startup class ConfigureServicee() method, add services for session and its backing store,
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddDistributedMemoryCache();
- services.AddSession();
- }
Add the session middleware in Configure() method,
- public void Configure(
- IApplicationBuilder app,
- IHostingEnvironment env)
- {
- app.UseSession();
- app.Use(async (context, next) =>
- {
- context.Session.SetString("GreetingMessage", "Hello Session State");
- await next();
- });
- app.Run(async (context) =>
- {
- var message = context.Session.GetString("GreetingMessage");
- await context.Response.WriteAsync($"{message}");
- });
- }
Discussion
We can use session in order to share information between different HTTP requests coming from a single browser. The data is stored in a cache (IDistributedCache implementation to be specific) and accessed via HttpContext.Session property.
A cookie is stored in browser to correlated the HTTP requests. The default name of this cookie is .AspNet.Session.
During the configuration of session services we can set various properties,
- HttpOnly - sets whether cookie is accessible through JavaScript. Default is true, which means it can’t be accessed via scripts on the client-side.
- Name - used to override the default cookie name.
- SecurePolicy - determines if session cookie is only transmitted via HTTPS requests.
- IdleTimeout - sets the time for session expiry, each request resets the timeout. Default is 20 mintues.
Shamsher SinghPosted Sep 6, 2019, 12:28 AM
How to handle if session timeout in Ajax call
David Alejandro García GarcíaPosted May 10, 2018, 10:49 AM
Can you please help with a sessions issue with asp net core 2? https://www.c-sharpcorner.com/forums/aspnet-core-2-no-service-for-httpcontext-sessions-issue
Vignesh ManiPosted Oct 9, 2017, 6:18 PM
Nice one. Thank you for sharing