Redirect to specific page after session expires (MVC4)
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();
}
}