asp.net-mvc-4 – 会话到期后重定向到特定页面(MVC4)

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

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...