Techiehook Techiehook
Updated date Jul 23, 2024
In this article, we will learn how to configure session timeout in the ASP.NET Core application.

Download File(s):

SessionNetCoreApplication.rar

How do you implement Session Timeout in ASP.NET Core?

To implement session timeout in an ASP.NET Core application, we must configure the session middleware and set the timeout period. The default session timeout is 20 minutes in ASP.NET Core, we can also override the timeout using IdleTimeout property.

Step 1: Create an ASP.NET Core project

Create a new ASP.NET Core application using Visual Studio 2022 IDE. Open VS 2022 -> Create a New Project -> Select "ASP.NET Core Web App (Model-View-Controller)" -> Enter "Project Name" -> Click "Create".

Step 2: Configure Session Timeout

In the program.cs file, we configure the services to add session options, including the timeout duration.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddDistributedMemoryCache(); // Use a distributed cache to store session data

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30); // Set session timeout
    options.Cookie.HttpOnly = true; // Make the session cookie HTTP-only
    options.Cookie.IsEssential = true; // Make the session cookie essential    
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseSession(); // Add this line to enable session handling

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Step 3: Use Session in Controller and View

We can now use the session in your controllers or pages. For example, in a controller:

using Microsoft.AspNetCore.Mvc;
using SessionNetCoreApplication.Models;
using System.Diagnostics;

namespace SessionNetCoreApplication.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            // Set Session using key and value
            HttpContext.Session.SetString("_Name", "Smith J");
          
            return View();
        }

        public IActionResult Privacy()
        {
            // Get session value using key
            var name = HttpContext.Session.GetString("_Name");
            ViewBag.UserName = name;

            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

Privacy.cshtml

We can display the UserName in Privacy.cshtml page using @ViewBag.UserName as shown below,

@{
    ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>


<p>
    <b>Name:</b> @ViewBag.UserName;
</p>

<p>Use this page to detail your site's privacy policy.</p>

When the session times out, the stored data will be lost. We can handle session expiration by checking for the presence of session data and redirecting the user to a login page or showing an appropriate message in your applications.

Output:

When you run the application, you can see the "Smith J" value in the "Privacy" screen.

By using these steps, we can configure and manage session timeout in your ASP.NET Core application easily.

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!