Session State in ASP.NET Core, .NET 5
This article describes some key steps needed to make use of Session state on the ASP.NET Core platform.
Microsoft has a good article on Session and state management in ASP.NET Core. The Microsoft article covers wider issues beyond Session state and is a useful article to read.
Namespace
To access the Session data in your code, you will need to use the following namespace.
using Microsoft.AspNetCore.Http;
Storing data
The SessionExtensions class provides methods to store String and Int32.
// Storing a string
string someValue = "a value to store in session data";
HttpContext.Session.SetString("SomeKeyForString", someValue);
// Storing an int
int pageNumber = 10
HttpContext.Session.SetInt32("SomeKeyForInt", pageNumber);
There must be data that you are trying to store. If you pass a null
value, there will be a build-time error.
If you want to store a complex type, such as your own object, then you will need to specifiy how that should be serialized. An article from Ben Cull provides an example for a JSON object, as part of a page with more details on Session Data in ASP.NET MVC.
Clearing the data
To clear the data, use the Remove method from ISession.
HttpContext.Session.Remove("SomeKey");
Setup
In order to access HttpContext in a Controller, there is a little setup. The following is a summary from the Session state part of the Microsoft article.
In ConfigureServices
, add the following code as a starting point. This sets up the app to store Session data in memory on the machine that is running the application and it sets a default timeout for 30 minutes.
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
Also, in the Configure
method, add the following. I put it after app.UseAuthentication()
and app.UseAuthorisation()
setup and before app.UseEndpoints()
.
app.UseSession();
There are other ways to setup the options for Session data. See the Session options section of the Microsoft article for links to what you can configure.
Accessing State in a Razor view
If you want to access the Session data in a RazorView, e.g. Index.cshtml
, you need to do a little setup.
Firstly, configure access to the HttpContextAccessor
. In Startup.cs
, add the following to the ConfigureServices
method.
services.AddHttpContextAccessor();
Then, in the view, include the following at the top of the view.
@using Microsoft.AspNetCore.Http
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
Finally, within the view, use the following to access a value:
<p>
Example data:
@HttpContextAccessor.HttpContext.Session.GetString("SomeKeyForString")
</p>
Microsoft has an article about how to access HttpContext ASP.NET Core, which covers some other situations if you need access to HttpContext.