Redirect to specific page after session expires (MVC4)

chiapa picture chiapa · Aug 21, 2014 · Viewed 42.4k times · Source

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?

Answer

Kartikeya Khosla picture Kartikeya Khosla · Aug 21, 2014

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();
  }
}