ASP.NET Core 2.0 Session State

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,

Add the session middleware in Configure() method,

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.

Storing Objects

HttpContext.Session (or ISession that it implements) does not provide a built-in way to store complex objects, however, we can serialise objects into JSON strings to achieve this,

Now we can use these extension methods like below,

Accessing via Dependency Injection

To access session using dependency injection you could use IHttpContextAccessor (via constructor), which gives you access to HttpContext.

Source Code

GitHub

Up Next
    Ebook Download
    View all
    Learn
    View all