C#MVC4项目:当会话到期时,我想重定向到特定的页面.
经过一些研究,我在项目中将以下代码添加到Global.asax中:
- protected void Session_End(object sender,EventArgs e)
- {
- Response.Redirect("Home/Index");
- }
当会话过期时,它将在Response.Redirect(“Home / Index”)行引发异常;说在这种情况下,响应不可用
这里有什么问题?
解决方法
这是MVC中最简单的方法
在会话过期的情况下,在每个操作中,您必须检查其会话,如果它为空,则重定向到索引页.
在会话过期的情况下,在每个操作中,您必须检查其会话,如果它为空,则重定向到索引页.
这是覆盖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);
- }
- }
- [SessionExpire]
- public ActionResult Index()
- {
- return Index();
- }
- [SessionExpire]
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return Index();
- }
- }