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>
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);
}
}
Then in the Action you need to put attribute as below:
[CheckSessionTimeOut]
[Authorize(Roles = "Admin")]
public ViewResult Index()
{
//Code goes here
}
Or Just add attribute one time as below :
[CheckSessionTimeOut]
public class HomeController : Controller
{
public ActionResult Index()
{
return Index();
}
}
1 Comment(s)