You could create an action filter for this scenario.
public class SessionExpiredRedirect : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.Controller.ControllerContext.HttpContext.Session == null) // Or however you want to check for expired session.
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "Controller", "YourController" },
{ "Action", "YourAction" }
});
}
}
}
To use the filter you can either place the attribute specifically on the action method you want to redirect if the session has expired:
public class HomeController : Controller
{
[SessionExpiredRedirect]
public ActionResult Index()
{
}
}
Or in the FilterConfig.cs file:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new SessionExpiredRedirect());
}
}
In which case the attribute will be executed for all action methods.