Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to specific page after session expires (MVC4)

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?

like image 662
chiapa Avatar asked Aug 21 '14 10:08

chiapa


People also ask

How do you handle session timeout?

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.


1 Answers

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();
  }
}
like image 51
Kartikeya Khosla Avatar answered Sep 19 '22 05:09

Kartikeya Khosla