How to Use Session in ASP.NET Core

In this tutorial, we will explain how to use session in your ASP.NET Core application. In asp.net core sessions are enables us to save/store the user data at client side .this user data will store the dictionary on the server and we will use sessionId is used as a key.the sessionId will store at client-side cookie and cookies is sent with each every request

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:

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.

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.

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:

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.

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:

It’s also worth noting that in ASP.NET Core 1.0, you cannot currently mark the cookie as Secure.

Summary

In this post we learn about how to use session in Asp.net Core. 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.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *