AngularJS与ASP.NET MVC登录超时解决方案

问题:

1.在Action中判断Ajax请求的方法Request.IsAjaxRequest()始终是false

2.返回给前台StatusCode和HttpUnauthorizedResult,前台接收到的Status还是200,表示成功

解决解决方案:

1.查了一些资料后发现,后台判断是否Ajax请求是根据请求数据headers中的 X-Requested-With 来识别,按现说使用AngularJS$http服务请求应该会自动给加上才对啊(还有很多人反应使用jQuery也有此问题,我没去试,不知道是不是通病)。于是想办法在AngularJS所有Ajax请求之前都加上 X-Requested-With,这里使用$httpProvider.interceptors拦截的方式来做统一处理。

2.我后台使用的是ActionFilter方式统一处理需要校验登录,返回HttpUnauthorizedResult,但是前台接收到的status始终都是200。这里需要注意两点:a)需要手动设置Response的Status状态码; b)必须要在设置完成后执行Response.End()

前台请求、响应拦截器代码:

zmApp.config(function ($httpProvider) {
    $httpProvider.interceptors.push(['$rootScope', '$q', '$location', '$timeout',
        function ($rootScope, $q, $location, $timeout) {
            return {
                'request': function (config) {
                    //处理AJAX请求(否则后台IsAjaxRequest()始终false)
                    config.headers['X-Requested-With'] = 'XMLHttpRequest';
                    return config || $q.when(config);
                },
                'requestError': function (rejection) {
                    return rejection;
                },
                'response': function (response) {
                    return response || $q.when(response);
                },
                'responseError': function (response) {
                    console.log('responseError:' + response);
                    if (response.status === 401 || response.status === 403) {
                        abp.notify.error("会话超时,请重新登录!");
                        $timeout(function () { window.location = "/Login"; }, 3000);
                        return false;
                    }
                    else if (response.status === 500) {
                        $location.path('/error');
                        return false;
                    }
                    return $q.reject(response);
                }
            };
        }]);
});

后台ActionFilter代码:

public class LoginAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContextBase context = filterContext.HttpContext;
            HttpResponseBase response = filterContext.HttpContext.Response;
            HttpRequestBase request = filterContext.HttpContext.Request;
            if (context.Session["User"] == null)
            {
                if (request.IsAjaxRequest())
                    response.Status = "401 Session Timeout";
                else
                    response.Redirect("/Login");
                filterContext.Result = new HttpUnauthorizedResult();//这一行保证不再执行Action的代码
                response.End();//必须加上这句,否则返回前台status始终是200
                return;
            }
            base.OnActionExecuting(filterContext);
        }
    }