ASP MVC处理session过期

  ASP MVC开发过程中,需要处理session过期。但是若请求是AJAX,则不会跳转到登陆页,而是会将登陆页作为部分刷新的一部分返回。

  解决方法:

  在filter中判断请求头部的X-Requested-With字段是否为XMLHttpRequest,若为即是AJAX请求,则返回Content,并在其中增加<script>标签,其中完成信息的提示和页面的跳转。这样就不用返回error再改写每个AJAX的error回调函数。

  

 1 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
 2         {
 3             base.HandleUnauthorizedRequest(filterContext);
 4             if (filterContext == null)
 5             {
 6                 throw new ArgumentNullException("filterContext");
 7             }
 8             else
 9             {
10                 if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
11                 {
12                     filterContext.Result = new ContentResult() { Content= "<script>alert('您长时间没有操作,请重新登录');window.location.href = '../Login/index';</script>" };
13                 }
14                 else
15                 {
16                     filterContext.HttpContext.Response.Redirect("/Login/Index");
17                 }
18             }
19         }

猜你喜欢

转载自www.cnblogs.com/brisk/p/9056685.html