An introduction to Session storage in ASP.NET Core (2023)

A common requirement of web applications is the need to store temporary state data. In this article I discuss the use of Session storage for storing data related to a particular user or browser session.

Options for storing application state

When building ASP.NET Core applications, there are a number of options available to you when you need to store data that is specific to a particular request or session.

One of the simplest methods is to use querystring parameters or post data to send state to subsequent requests. However doing so requires sending that data to the user's browser, which may not be desirable, especially for sensitive data. For that reason, extra care must be taken when using this approach.

Cookies can also be used to store small bits of data, though again, these make a roundtrip to the user's browser, so must be kept small, and if sensitive, must be secured.

For each request there exists a property Items on HttpContext. This is an IDictionary<string, object> which can be used to store arbitrary objects against a string key. The data stored here lasts for just a single request, so can be useful for communicating between middleware components and storing state related to just a single request.

Files and database storage can obviously be used to store state data, whether related to a particular user or the application in general. However they are typically slower to store and retrieve data than other available options.

Session state relies on a cookie identifier to identify a particular browser session, and stores data related to the session on the server. This article focuses on how and when to use Session in your ASP.NET Core application.

(Video) C# - How To Use Session Variables In .NET Core 6.0

Session in ASP.NET Core

ASP.NET Core supports the concept of a Session out of the box - the HttpContext object contains a Session property of type ISession. The get and set portion of the interface is shown below (see the full interface here):

public interface ISession{ bool TryGetValue(string key, out byte[] value); void Set(string key, byte[] value); void Remove(string key);}

As you can see, it provides a dictionary-like wrapper over the byte[] data, accessing state via string keys. Generally speaking, each user will have an individual session, so you can store data related to a single user in it. However you cannot technically consider the data secure as it may be possible to hijack another user's session, so it is not advisable to store user secrets in it. As the documentation states:

You can’t necessarily assume that a session is restricted to a single user, so be careful what kind of information you store in Session.

Another point to consider is that the session in ASP.NET Core is non-locking, so if multiple requests modify the session, the last action will win. This is an important point to consider, but should provide a significant performance increase over the locking session management used in the previous ASP.NET 4.X framework.

Under the hood, Session is built on top of IDistributedCache, which can be used as a more generalised cache in your application. ASP.NET Core ships with a number of IDistributedCache implementations, the simplest of which is an in-memory implementation, MemoryCache, which can be found in the Microsoft.Extensions.Caching.Memory package.

MVC also exposes a TempData property on a Controller which is an additional wrapper around Session. This can be used for storing transient data that only needs to be available for a single request after the current one.

(Video) ASP NET - SessionState

Configuring your application to use Session

In order to be able to use Session storage in your application, you must configure the required Session services, the Session middleware, and an IDistributedCache implementation. In this example I will be using the in-memory distributed cache as it is simple to setup and use, but the documentation states that this should only be used for development and testing sites. I suspect this reticence is due it not actually being distributed and the fact that app restarts will clear the session.

First, add the IDistributedCache implementation and Session state packages to your project.json:

dependencies: { "Microsoft.Extensions.Caching.Memory" : "1.0.0", "Microsoft.AspNetCore.Session": "1.0.0"}

Next, add the required services to Startup in ConfigureServices:

public void ConfigureServices(IServiceCollection services){ services.AddMvc(); services.AddDistributedMemoryCache(); services.AddSession();}

Finally, configure the session middleware in the Startup.Configure method. As with all middleware, order is important in this method, so you will need to enable the session before you try and access it, e.g. in your MVC middleware:

public void Configure(IApplicationBuilder app){ app.UseStaticFiles(); //enable session before MVC app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });}

With all this in place, the Session object can be used to store our data.

Storing data in Session

As shown previously, objects must be stored in Session as a byte[], which is obviously not overly convenient. To alleviate the need to work directly with byte arrays, a number of extensions exist for fetching and setting int and string. Storing more complex objects requires serialising the data.

(Video) An Intro to ASP.NET Core Minimal API - Chalkboard Session About State Management Concepts

As an example, consider the simple usage of session below.

public IActionResult Index(){ const string sessionKey = "FirstSeen"; DateTime dateFirstSeen; var value = HttpContext.Session.GetString(sessionKey); if (string.IsNullOrEmpty(value)) { dateFirstSeen = DateTime.Now; var serialisedDate = JsonConvert.SerializeObject(dateFirstSeen); HttpContext.Session.SetString(sessionKey, serialisedDate); } else { dateFirstSeen = JsonConvert.DeserializeObject<DateTime>(value); } var model = new SessionStateViewModel { DateSessionStarted = dateFirstSeen, Now = DateTime.Now }; return View(model);}

This action simply simply returns a view with a model that shows the current time, and the time the session was initialised.

First, the Session is queried using GetString(key). If this is the first time that action has been called, the method will return null. In that case, we record the current date, serialise it to a string using Newtonsoft.Json, and store it in the session using SetString(key, value).

On subsequent requests, the call to GetString(key) will return our serialised DateTime which we can set on our view model for display. After the first request to our action, the DateSessionStarted property will differ from the Now property on our model:

An introduction to Session storage in ASP.NET Core (1)

This was a very trivial example, but you can store any data that is serialisable to a byte[] in the Session. The JSON serialisation used here is an easy option as it is likely already used in your project. Obviously, serialising and deserialising large objects on every request could be a performance concern, so be sure to think about the implications of using Session storage in your application.

(Video) How to use Session in ASP.NET Core

Customising Session configuration

When configuring your session in Startup, you can provide an instance of StartupOptions or a configuration lambda to either the UseSession or AddSession calls respectively. This allows you to customise details about the session cookie that is used to track the session in the browser. For example you can customise the cookie name, domain, path and how long the session may be idle before the session expires. You will likely not need to change the defaults, but it may be necessary in some cases:

services.AddSession(opts => { opts.CookieName = ".NetEscapades.Session"; opts.IdleTimeout = TimeSpan.FromMinutes(5); });

Note the cookie name is not the default .AspNetCore.Session:

An introduction to Session storage in ASP.NET Core (2)

It's also worth noting that in ASP.NET Core 1.0, you cannot currently mark the cookie as Secure. This has been fixed here so should be in the 1.1.0 release (probably Q4 206/ Q1 2017).

Summary

In this post we saw an introduction to using Session storage in an ASP.NET Core application. We saw how to configure the required services and middleware, and to use it to store and retrieve simple strings to share state across requests.

As mentioned previously, it's important to not store sensitive user details in Session due to potential security issues, but otherwise it is a useful location for storage of serialisable data.

(Video) How To Use Sessions in ASP.NET Core

Further Reading

FAQs

How to use session storage in ASP.NET Core? ›

To enable the session middleware, Program.cs must contain:
  1. Any of the IDistributedCache memory caches. The IDistributedCache implementation is used as a backing store for session. For more information, see Distributed caching in ASP.NET Core.
  2. A call to AddSession.
  3. A call to UseSession.
Feb 13, 2023

How to get value from session storage in C#? ›

Syntax
  1. Save Data to Session Storage. sessionStorage.setItem("key", "value");
  2. Read Data from Session Storage. let lastname = sessionStorage.getItem("key");
  3. Remove Data from Session Storage. sessionStorage.removeItem("key");
  4. Remove All (Clear session Storage) sessionStorage.clear();

How to get data from session in ASP.NET Core? ›

  1. using Microsoft.AspNetCore.Http;
  2. if (HttpContext.Session.GetString("Name") != null)
  3. name = HttpContext.Session.GetString("Name");
  4. if (HttpContext.Session.GetInt32("Age") != null)
  5. age = (Int32)HttpContext.Session.GetInt32("Age");

Where is session data stored in .NET core? ›

A session state keeps the data as long as the cookie is configured to last. The default session state version in ASP.NET Core stores the session data in the memory (RAM) of the web server.

What data can be stored in session storage? ›

You can use session storage when the data that needs to be saved is sensitive. User authentication is an example of data that you would like to clear as soon as the user closes the tab.

When should I use session storage? ›

For most cases, we use the local Storage object if we want some data to be on the browser. If we want it on the server, then we use it, and the session storage is used when we want to destroy the data whenever that specific tab gets closed or the season is closed by the user.

How do I get all data from session storage? ›

To access the elements from session storage in javascript, we use getItem() method which helps us to access elements that are stored in the session storage object. The getItem() method belongs to the storage object. It can be a local storage object or a session Storage object.

What is the difference between session storage and local storage in C#? ›

Session Storage objects can be accessed using the sessionStorage read-only property. The difference between sessionStorage and localStorage is that localStorage data does not expire, whereas sessionStorage data is cleared when the page session ends.

What is the difference between local storage and session storage? ›

sessionStorage is similar to localStorage ; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends. Whenever a document is loaded in a particular tab in the browser, a unique page session gets created and assigned to that particular tab.

How to get data from session in ASP.NET c#? ›

And using the session keys we are getting the values.
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. for (int i = 0; i < Session.Count; i++)
  4. {
  5. string value = "Key: " + Session.Keys[i] + ", Value: " + Session[Session.Keys[i]].ToString();
  6. Response.Write(value);
  7. }
  8. }
Aug 19, 2015

How to manage session in ASP.NET c#? ›

Application State
  1. Step 1: Open Visual Studio.
  2. Step 2: Click on New Project > WEB > ASP.NET Empty Web Application.
  3. Step 3: Click on Solution Explorer.
  4. Step 4: Right-click on Add > New Item > Web Form. ...
  5. Step 5: Add the code to WebForm1.
  6. Step 6: Add the code to WebForm2.
  7. Step 7: Now set the session in Web. ...
  8. Output:
Sep 1, 2020

How do I see what is stored in session? ›

View sessionStorage keys and values
  1. In DevTools, click the Application tab to open the Application tool. The Manifest panel is shown by default.
  2. Expand the Session Storage menu.
  3. Click a domain to view the key-value pairs.
  4. Click a row of the table to view the value in the viewer below the table.
Jun 14, 2023

How to store user data in session? ›

There are several ways to store user data in the browser: 1. Cookies: Cookies are small text files that can store data such as user preferences, login information, and shopping cart items. They are typically used to store session data that is only available while the user's browser is open.

Is session storage stored on the server? ›

It's not stored on the server, since we're still in client side when you're talking about Window. sessionStorage .

How to set session time in ASP.NET Core? ›

Note: The default Session Timeout in ASP.Net Core is 20 minutes.
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services. AddMvc();
  4. //Set Session Timeout. Default is 20 minutes.
  5. services.AddSession(options =>
  6. {
  7. options.IdleTimeout = TimeSpan.FromMinutes(30);
  8. });
Nov 18, 2021

How do I use session storage? ›

To get an element from session storage, firstly we need to create an element and store it in the session storage. Later, we can retrieve it. The methods of the storage object are setItem(), getItem(), removeItem(), and clear(). setItem() is used to set the value for the session storage item.

How to keep session alive in ASP.NET Core? ›

Keep ASP.NET session alive using jQuery

As very similar alternative we can use jQuery for same task. In this example, I will use jQuery post function to make a request to web server. Pages requested with POST are not cached, so we don't need unique URL like in previous JavaScript example.

How to store function in session storage? ›

setItem() This method is called to store values in session storage. This method takes in the key and values as parameters. In the above function, name is the key, while John Smith is the value.

Videos

1. ASP.NET Core - Session Data
(Industrial IT and Automation)
2. Sessions in ASP.NET Core 1.0
(Webucator)
3. Handling Session in Asp.Net Core MVC
(Learning Programming Tutorial)
4. StateServer asp.net session state mode management Part 65
(kudvenkat)
5. Asp.net session state Part 62
(kudvenkat)
6. Get and Set Session in ASP.Net Core Razor Pages
(ASPSnippets)

References

Top Articles
Latest Posts
Article information

Author: Gov. Deandrea McKenzie

Last Updated: 05/10/2023

Views: 5820

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Gov. Deandrea McKenzie

Birthday: 2001-01-17

Address: Suite 769 2454 Marsha Coves, Debbieton, MS 95002

Phone: +813077629322

Job: Real-Estate Executive

Hobby: Archery, Metal detecting, Kitesurfing, Genealogy, Kitesurfing, Calligraphy, Roller skating

Introduction: My name is Gov. Deandrea McKenzie, I am a spotless, clean, glamorous, sparkling, adventurous, nice, brainy person who loves writing and wants to share my knowledge and understanding with you.