C# MVC4 project: I want to redirect to a specific page when the session expires.
After some research, I added the following code to the Global.asax
in my project:
protected void Session_End(object sender, EventArgs e)
{
Response.Redirect("Home/Index");
}
When the session expires, it throws an exception at the line Response.Redirect("Home/Index");
saying The response is not available in this context
What's wrong here?
Use some jquery that keys off of your session timeout variable in the web. config. You can use this Jquery delay trick that when a specific time occurs (x number of minutes after load of the page), it pops up a div stating session timeout in x minutes. Nice, clean and pretty simple.
The easiest way in MVC is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Index page.
For this purpose you can make a custom attribute as shown :-
Here is the Class which overrides ActionFilterAttribute.
public class SessionExpireAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check sessions here
if( HttpContext.Current.Session["username"] == null )
{
filterContext.Result = new RedirectResult("~/Home/Index");
return;
}
base.OnActionExecuting(filterContext);
}
}
Then in action just add this attribute as shown :
[SessionExpire]
public ActionResult Index()
{
return Index();
}
Or Just add attribute only one time as :
[SessionExpire]
public class HomeController : Controller
{
public ActionResult Index()
{
return Index();
}
}
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