I would like to know the best way to handle and implement session time outs in MVC. I have setup my app so that it can handle the "RememberMe" when the user authenticate. I also stores some variables in Context.Session["myvar"];
I run into a problem when my session has expired but my authentication cookie has not yet expired.
My first thought was to check the session stat on on action request; but that seems like a lot of code. Is there a good place to check the session state once? What are other ways to handle a session time out? I would like the user to be redirected to the login page when a session has timedout. or have the session variables reloaded if the user is still logged in.
Is there a good place to check the session state once
Sure, a custom Authorize attribute looks like a great place:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authroized = base.AuthorizeCore(httpContext);
if (!authroized)
{
// the user is not authenticated or the forms authentication
// cookie has expired
return false;
}
// Now check the session:
var myvar = httpContext.Session["myvar"];
if (myvar == null)
{
// the session has expired
return false;
}
return true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With