This asp.net MVC core tutorial, we will learn how to set up a session state in ASP.NET Core and MVC Core Web applications.
Set up session state in our ASP.NET Core and MVC Core Web applications
Follow the below steps to set up a session state in our ASP.NET Core and MVC Core Web applications.
Step-1: New project:
Open Visual Studio and select File >> New Project.
The “New Project” window will pop up. Select .NET Core and select “ASP.NET Core Web Application”. Name our project and click “OK”.
A “New Project” window will pop up. Select Web Application and click “OK”, as shown below.
Step-2: Dependencies
Once our project is ready, open Solution Explorer, right-click “dependencies”, and click “Manage NuGet Packages.”.
Packages Required
We need to install the stable version of “Microsoft.AspNetCore.Session” from the NuGet Package Manager. Then only we can access the session state in ASP.NET Core. Click on the “Install” button.
Step-3: HomeControllers
Now, double click “HomeControllers.cs”. The following is an example of a session sharing in ASP.NET Core.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Session_State.Models;
namespace Session_State.Controllers
{
public class HomeController : Controller
{
const string SessionName = "_Name";
const string SessionAge = "_Age";
public IActionResult Index()
{
HttpContext.Session.SetString(SessionName, "Satya");
HttpContext.Session.SetInt32(SessionAge, 24);
return View();
}
public IActionResult About()
{
ViewBag.Name = HttpContext.Session.GetString(SessionName);
ViewBag.Age = HttpContext.Session.GetInt32(SessionAge);
ViewData["Message"] = "Asp.Net Core !!!.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Step 4: Startup.cs
Now, double click “Startup.cs” to configure the services. The very first step we need to take is to add the session service to the container so that we can add the services in the “configureServices” function.
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(1);//You can set Time
});
services.AddMvc();
}
Configure the HTTP Request Pipeline
Now, in the same class, we add “app.Usersession()” inside the “configure” function so that it gets called by the runtime.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
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:
Now, run the project. We will see the output of an Active Session, as below.
Let us set “one” minute as the Session TimeOut in the “ConfigureServices” function of the “Startup.cs” class.
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(1);//You can set Time
});
Session Expires:
You may like following asp.net tutorials:
- Generate One Time Password (OTP) in Asp.Net using C#.Net
- Gridview in asp.net
- How to show Progress Bar in Asp.Net using jQuery?
- Asp.Net MVC 5 Cascading DropDownList Using jQuery
- Asp.Net MVC Life Cycle and Various State Management Techniques in Asp.Net MVC
- Asp.Net MVC Techniques to transfer data from Controller to View
- Steps to archive log files using NLog with ASP.NET Core
- Asp.Net response.redirect example
- Validation of viewstate MAC failed error in Asp.net
- How to Implement Log4Net in ASP.NET Core Application
Here we discussed how to setup Session in ASP.NET Core and MVC Core Web applications and Result before a session and after a session.
MVP Award Winner | Community Author & Contributor | Software Developer | Most Valuable Blogger(MVB)