-
ASP.NET MVC: How to Check Session Timeout and Redirect to Login Page
over 9 years ago
-
over 8 years ago
this isnt working , ? why i follow carefully every instruction
-
over 9 years ago
The following post captures the implementation details to manage session timeout in ASP.NET MVC. If session has expired we will redirect the user to login page
First you need to make modificaions in web.config as below:
- <system.web>
- <sessionstate mode="InProc" timeout="2" cookieless="false"></sessionstate>
- <authentication mode="Forms">
- <forms loginurl="~/Home/Login" timeout="1">
- </forms></authentication>
- </system.web>
<system.web> <sessionstate mode="InProc" timeout="2" cookieless="false"></sessionstate> <authentication mode="Forms"> <forms loginurl="~/Home/Login" timeout="1"> </forms></authentication> </system.web>
Next you need to make a custom attribute as shown below. Here is the code which overrides ActionFilterAttribute.
- [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
- public class CheckSessionTimeOutAttribute : ActionFilterAttribute
- {
- public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
- {
- var context = filterContext.HttpContext;
- if (context.Session != null)
- {
- if (context.Session.IsNewSession)
- {
- string sessionCookie = context.Request.Headers["Cookie"];
- if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
- {
- FormsAuthentication.SignOut();
- string redirectTo = "~/Home/Login";
- if (!string.IsNullOrEmpty(context.Request.RawUrl))
- {
- redirectTo = string.Format("~/Home/Login?ReturnUrl={0}",HttpUtility.UrlEncode(context.Request.RawUrl));
- }
- filterContext.HttpContext.Response.Redirect(redirectTo , true);
- }
- }
- }
- base.OnActionExecuting(filterContext);
- }
- }
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public class CheckSessionTimeOutAttribute : ActionFilterAttribute { public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { var context = filterContext.HttpContext; if (context.Session != null) { if (context.Session.IsNewSession) { string sessionCookie = context.Request.Headers["Cookie"]; if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) { FormsAuthentication.SignOut(); string redirectTo = "~/Home/Login"; if (!string.IsNullOrEmpty(context.Request.RawUrl)) { redirectTo = string.Format("~/Home/Login?ReturnUrl={0}",HttpUtility.UrlEncode(context.Request.RawUrl)); } filterContext.HttpContext.Response.Redirect(redirectTo , true); } } } base.OnActionExecuting(filterContext); } }
Then in the Action you need to put attribute as below:
Or Just add attribute one time as below :
over 8 years ago
this isnt working , ? why i follow carefully every instruction
1 Comment(s)