Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Session State in ASP.NET Core and MVC Core

DZone's Guide to

Session State in ASP.NET Core and MVC Core

Read on to learn how to use your C# coding prowess to set up session state in your ASP.NET Core and MCV Core web applications.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Session State

We can use session state to save and store user data while the user browses your web app. We already know that in previous versions of ASP.NET we can store session as key value pairs like this: “Session[“Name”] = “Rajeesh Menoth”” and Implement this in an easy way.But in the latest version of ASP.NET or ASP.NET Core, we need to make a few configurations for accessing and enabling session state in the application. The main purpose session is maintaining user data in the browser's memory because HTTP is a stateless protocol.

Package Required

We need to install the stable version of  “Microsoft.AspNetCore.Session” from the Nuget Package Manager. Then only we can access session state in ASP.NET Core 1.1.

Image title

Microsoft.AspNetCore.Session

.csproj

In “.csproj” we can check all the installed packages and versions details in ASP.NET Core 1.1.

<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />

Assemblies Required

These are the assemblies mainly required for accessing the functionality of Session State, MVC, JSON, etc. 

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

Home Controller

The following code is an example of a session sharing in ASP.Net Core 1.1.

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace SessionInCore.Controllers
{
    public class HomeController : Controller
    {
        const string SessionKeyName = "_Name";
        const string SessionKeyAge = "_Age";
        const string SessionKeyDate = "_Date";

        public IActionResult Index()
        {
            HttpContext.Session.SetString(SessionKeyName, "Rajeesh Menoth");
            HttpContext.Session.SetInt32(SessionKeyAge, 28);
            // Requires you add the Set extension method mentioned in the SessionExtensions static class.
            HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);

            return View();
        }

        public IActionResult About()
        {
            ViewBag.Name = HttpContext.Session.GetString(SessionKeyName);
            ViewBag.Age = HttpContext.Session.GetInt32(SessionKeyAge);
            ViewBag.Date = HttpContext.Session.Get<DateTime>(SessionKeyDate);

            ViewData["Message"] = "Session State In Asp.Net Core 1.1";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "My Contact Details";

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }

    }

    public static class SessionExtensions
    {
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) :
                                  JsonConvert.DeserializeObject<T>(value);
        }
    }
}

The following code lists the Key name as “SessionKeyName” and the Value name as “Rajeesh Menoth.” So we can set the Session String “Key” and “Value” with the SetString(“Key”,”Value”) method.

const string SessionKeyName = "_Name";
HttpContext.Session.SetString(SessionKeyName, "Rajeesh Menoth");

The following code contains a similar Session code in the older version of ASP.NET.

 Session["Name"] = "Rajeesh Menoth"; 

A simple way we can assign and get the session string value is by using the GetString(Name) Method.

 ViewBag.Name = HttpContext.Session.GetString(SessionKeyName); 

Using the following code, we can set and get serializable objects to session in our application.

//Accessing Extension Method.
HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);
//Example of Extension Method.
 public static class SessionExtensions
    {
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) :
                                  JsonConvert.DeserializeObject<T>(value);
        }
    }

Configure Services

To configure services, the first step we need to take is to add the session services to the container. So we can add the services in the “ConfigureServices” method in the “Startup.cs” class in our application.

public void ConfigureServices(IServiceCollection services)
        {
            //In-Memory
            services.AddDistributedMemoryCache();
            services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(1);
            });              
            // Add framework services.
            services.AddMvc();
        }

Configure the HTTP Request Pipeline

We add the “app.UseSession()” inside the Configure Method in the “Startup.cs” class so that it gets called by the runtime. One more advantage is that we can use this method to configure the HTTP request pipeline in our application.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Out Put 1 – Active Session

Image title

Session Active

Out Put 2 – Session Expired

We set 1 minute as the Session Timeout in the ConfigureServices method in the startup.cs class.

 services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(1);//Session Timeout.
            });


Image title

Session Expire

References

Conclusion

We have learned how to create session state in ASP.NET Core and MVC Core. I hope you liked this article. Please share your valuable suggestions and feedback.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
web dev ,asp.net ,session ,state

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}