Ajax

AJAX即“Asynchronous Javascript + XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术。

 


 在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‘;
              }
  });