How to redirect page automatically on session expire page when session expired in asp.net core 6.0 C#?
Loading
How to redirect page automatically on session expire page when session expired in asp.net core 6.0 C#?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jignesh KumarRank #91 · 22.9K reputationPosted Feb 16, 2023, 6:28 AM EST
Hi Piyush,
Please do needful as below in startup.cs page,
services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.IsEssential = true; }); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = "YourCookieName"; options.Cookie.HttpOnly = true; options.ExpireTimeSpan = TimeSpan.FromMinutes(30); options.SlidingExpiration = true; options.LoginPath = "/Account/Login"; options.LogoutPath = "/Account/Logout"; options.AccessDeniedPath = "/Account/AccessDenied"; options.Events.OnRedirectToLogin = context => { context.Response.StatusCode = 401; return Task.CompletedTask; }; });Add the following code to the Configure method in the Startup.cs file:
Create new SessionExpiredMiddleware.cs file:
public class SessionExpiredMiddleware { private readonly RequestDelegate _next; public SessionExpiredMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { var sessionFeature = context.Features.Get(); if (sessionFeature == null || sessionFeature.Session == null) { await context.ChallengeAsync(); return; } await _next(context); } }piyush goyal83 reputationPosted Feb 16, 2023, 7:18 AM EST
Thanks for your time and help but we don't have the startup.cs in core 6.0.
Can you please provide me a running application with this functionality only in core 6.0
Naimish MakwanaRank #324 · 7.7K reputationPosted Feb 16, 2023, 6:06 AM EST
Hello Piyush,
Please refer below link:
https://stackoverflow.com/a/66107308/3054222
https://stackoverflow.com/a/71474464/3054222
Thanks
Naimish
Tuhin PaulRank #7 · 71.9K reputationPosted Feb 16, 2023, 6:08 AM EST
Bro! You have to follow 3 easy steps:
1. Create a new Razor page named "SessionExpired.cshtml" that will be displayed when the session expires. This page should include a message informing the user that their session has expired and providing a link to return to the login page.
2. In the Program.cs file, configure the session middleware to set the timeout for the session and to redirect to the SessionExpired page when the session expires. You can also set the cookie name and other options as needed.
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; var builder = WebApplication.CreateBuilder(args); builder.Services.AddSession(options => { options.IdleTimeout = TimeSpan.FromSeconds(30); // Set the timeout for the session options.Cookie.Name = ".MyApp.Session"; // Set the name of the cookie }); builder.Services.AddControllersWithViews(); builder.Services.AddRazorPages(); var app = builder.Build(); app.UseSession(); // Use the session middleware app.Use(async (context, next) => { var session = context.Session; if (session != null && !session.IsAvailable) { // Redirect to the SessionExpired page if the session has expired context.Response.Redirect("/SessionExpired"); return; } await next(); }); app.UseStaticFiles(); app.UseRouting(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.MapRazorPages(); app.Run();3. Finally, in your other Razor pages or controllers, use the session to store and retrieve data as needed. The session will automatically expire after the timeout period specified in the configuration. If the user tries to access a page with an expired session, they will be redirected to the SessionExpired page.
public class MyController : Controller { public IActionResult Index() { // Set a value in the session HttpContext.Session.SetString("MyKey", "MyValue"); // Retrieve a value from the session var value = HttpContext.Session.GetString("MyKey"); return View(); } }DONE!
Your users will be automatically redirected to the SessionExpired page when their session expires.
Tuhin PaulRank #7 · 71.9K reputationPosted Feb 16, 2023, 6:58 AM EST
Thanks @Jignesh, for sharing your implementation.