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 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 session is maintaining user data in memory because of 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 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 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 the example of 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);
-
- 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 "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.
-
- HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);
-
- 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 "ConfigureServices" method in "Startup.cs" class in our application.
- public void ConfigureServices(IServiceCollection services)
- {
-
- services.AddDistributedMemoryCache();
- services.AddSession(options => {
- options.IdleTimeout = TimeSpan.FromMinutes(1);
- });
-
- 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 mins as the Session Timeout in "ConfigureServices" method in Startup.cs class.
- services.AddSession(options => {
- options.IdleTimeout = TimeSpan.FromMinutes(1);
- });
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.