加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 18:57:21 所属栏目:asp.Net 来源:网络整理
导读:C#MVC4项目:当会话到期时,我想重定向到特定的页面. 经过一些研究,我在项目中将以下代码添加到Global.asax中: protected void Session_End(object sender,EventArgs e){ Response.Redirect("Home/Index");} 当会话过期时,它将在Response.Redirect(“Home /
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();
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读