il_fullxfull.424179836_ecli

For those who are new to Asp.net, session state is a way to store and retrieve user specific values. This state is linked to a user and it’s lifetime equals the duration of the user ‘s session. The session state can be programmatically accessed during the different requests of the user.

When you enable the session state, you have to be aware that this state has to be persisted in order to keep the state between requests. There are a few options available. You can persist to your web server memory. This method will work if you have a single server, but when you have multiple servers, you can’t do this. In a web farm scenario, you don’t know that every request of your user will be handled by the same server. In order to make the session state work, you will have to set up a distributed session.

Setting up the session state

In Asp.net Core you have to opt-in services. By default, you won’t have a session state. You will have to enable and configure it in the ConfigureServices method. The middleware that will manage the session state can be found in the “Microsoft.AspNetCore.Session” nuget package. You will need to add this to you project.json. You will also need to import the persistence mechanism for the session. The in-memory storage can be located in the “Microsoft.Extensions.Caching.Memory” nuget package.

nuget package for session state

public void ConfigureServices(IServiceCollection services)
{

      // Add framework services.
     services.AddMemoryCache();
     services.AddSession(options =>
     {
         options.IdleTimeout = TimeSpan.FromMinutes(10);
     });
     services.AddMvc();
}

The AddSession method exposes a delegate which can be used to configure the session even further. In this example I’ve set the timeout period to 10 minutes (default is 20 minutes). When the user is idle for 10 minutes, the session will expire and all the content that is related to this user his session will be removed.

We successfully added the session to the application. The next step is to activate the session in the application. This is done in the Configure method by calling the “UseSession” method on the app variable.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
     app.UseSession();
}

How to use the session state

The session is now ready to use. The session can be found in the HttpContext. To add a value to it, you can use the “Set” method. This method accepts a string this will identify (key) the value. The other parameter is a byte[].  All items are actually stored as a byte array. This is done to make sure that the data can be stored on remote servers when you are using a distributed session. So when you want to store complex objects in the session, you have to serialize them in order to store them.

For simple string and int variables, you can add the “Microsoft.AspNetCore.Http” namespace. This will add the extension methods SetInt32 and SetString to the Session object.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

namespace WebApplication9.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            HttpContext.Session.SetInt32("somekey", 1);

            var i = HttpContext.Session.GetInt32("somekey");

            return View();
        }
    }
}

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>