Handling session timeout in ajax

2019-04-13 18:34发布

问题:

In my MVC app I have the following attribute that checks for logged on users:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
       ....
       if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
       {
               filterContext.Result = new Http403Result();
               filterContext.HttpContext.Response.StatusCode = 403;
       }
...
}

Layout.cshtml

    $("body").ajaxError(
        function (e, request, settings, exception) {
            alert('in');
            if (request.status == 403) {
                window.location = '@Url.Action("LogOn", "Account", new {area = "", msg = "forbidden", returnUrl = HttpContext.Current.Request.RawUrl})' + window.location.hash;
                return;
            }
            if (request.status == 500) {
                window.location = '@Url.Action("AccessDenied", "Error")';
                return;
            }
            if (request.status == 410) {
                window.location = '@Url.Action("Deleted", "Error")';
                return;
            }
            window.location = '@Url.Action("Index", "Error")';
        });

but for some reason alert("in") never gets hit even when 403 code is thrown (from ajax request):

回答1:

Wrap the Ajax Error event in DOM Ready function

$(document).ready(function () {
    $(document).ajaxError(function (e, xhr, settings) {
        debugger;
    });
});

Or check here