Introduction
In this article, we will explain how to create a "Session State in ASP.NET Core and MVC Core".
Session State
In Session State, we can use to save and store user data while the user browses your web app. We already know that in previous versions of ASP.NET, we could store a session as key-value pair like this "Session["Name"] = "Rajeesh Menoth" and implement it in an easy way. But in the latest version of ASP.NET or ASP.NET Core, we need to do a few configurations for accessing and enabling Session State in the application. The main purpose of a session is to maintain user data in memory because HTTP is a stateless protocol.
Before reading this article, you must read the articles given below for ASP.NET Core knowledge.
Package Required
We need to install the stable version of “Microsoft.AspNetCore.Session” from Nuget Package Manager. Then only we can access Session State in ASP.NET Core 1.1.
.csproj
In “.csproj” we can check all the installed packages and version 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 sharing session 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 contains the Key name as "SessionKeyName" & Value name as "Rajeesh Menoth". So we can set the Session String "Key" and "Value" in SetString("Key","Value").
const string SessionKeyName = "_Name";
HttpContext.Session.SetString(SessionKeyName, "Rajeesh Menoth");
The following code contains a similar Session code as an older version of ASP.NET.
Session["Name"] = "Rajeesh Menoth";
We can Assign and Get the Session string value using the "GetString(Name)" Method in a simple way.
ViewBag.Name = HttpContext.Session.GetString(SessionKeyName);
In the following way, 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
The first step is we need 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 "Startup.cs" Class because it gets called by the runtime. One more advantage is 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?}");
});
}
Output. Active Session
Output. Session Expired
We set 1 minute as the Session Timeout in the "ConfigureServices" method in Startup.cs class.
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(1); // Session Timeout.
});
Reference
See Also
You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.
Conclusion
We 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.