ajax 请求登录超时跳转登录页解决方法

 在Filter里判断是否登录,如果未登录返回401状态

 public class SelfOnlyAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            HttpResponseBase response = filterContext.HttpContext.Response;
            HttpRequestBase request = filterContext.HttpContext.Request;

            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                //已经登录代码
            }
            else
            {
                if (!request.IsAjaxRequest()) 
                { 
                    string str = request.Url.AbsoluteUri.ToLower();
                    string str2 = "/login";
                    filterContext.Result = new RedirectResult(string.Format("{0}?returnUrl={1}", str2, str));
                }
                else
                {
                    response.SetStatus(401);
                }
                filterContext.Result = new HttpUnauthorizedResult(); //这一行保证不再执行Action的代码
                response.End(); //必须加上这句,否则返回前台status始终是200
                return;

            }
        }

    }

  

 

在全局js添加错误处理代码

   $("div").ajaxError(function(e,xhr,opt){
    
    alert(xhr.status+ " " + xhr.statusText);

           if(xhr.status=401){
                //TODO 未登录 跳转到登录页
                window.location.href = '/login';
              }
  });

  

posted @ 2015-04-03 18:24  usday  阅读(2201)  评论(0编辑  收藏  举报