什么HTTP响应代码是jQuery aJax错误处理程序考虑的错误'?

时间:2017-01-10 20:30:40

标签: javascript c# jquery asp.net ajax

我有一个标准的aJax回调到服务器:

$.ajax({
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        url: '/Apps/ResetDateAndCount',
        data: JSON.stringify({
            appName: app
        }),
        success: function (response) {
            $('.lastReset').text(response);
            $('.currentCount').text('0');
        },
        error: function (xhr, status, error) {
            alert("You are not authorized to perform that action");
        }
    });

从我的服务器(ASP.NET)我返回错误,如:

return Json(new { success = false, error = "You are not authorized to perform that action" });

Response.StatusCode = 401; return Json(new { success = false, error = "You are not authorized to perform that action" });

Response.StatusCode = 500; return Json(new { success = false, error = "You are not authorized to perform that action" });

错误处理程序error: function (xhr, status, error) 内部,当状态代码设置为500时,只有最后一次返回会被捕获为错误。

我想知道aJax实际上考虑了什么响应代码"错误"?

2 个答案:

答案 0 :(得分:8)

在进行AJAX调用时,任何超出区间[200,299]且不同于304的错误代码都被Response.StatusCode = 401; return Json(new { success = false, error = "You are not authorized to perform that action" }); 视为错误。

现在你当然会问我,这很好,花花公子,但为什么这不应该被认为是一个错误,毕竟我回到401之外的上述间隔所以它应该被视为错误:

error

非常简单:因为当您从ASP.NET MVC中的控制器操作返回401状态代码时,框架(更具体地说是ASP.NET Forms身份验证模块)将拦截此请求并最终将您重定向到登录表单产生200状态代码。是的,登录页面提供200 OK状态代码。在这种情况下,200位于区间内,因此不会调用success回调。您可以通过检查针对此特定情况的error回调中返回的登录页面的DOM来验证这一点。

现在将自己置于浏览器发出AJAX请求的角度:它将遵循服务器所做的所有重定向,直到它到达最终目的地。如果此最终目标状态代码超出了间隔且不同于304,那么您将调用replace回调。好的,现在事情开始变得更有意义了。

因此,如果我从控制器操作中返回401状态代码,那么您将要问我的下一个问题是如何调用错误回调,对吧?然后我会将你(:-))重定向到以下博文:Prevent Forms Authentication Login Page Redirect When You Don't Want It

答案 1 :(得分:1)

我建议检查标准HTTP代码列表。请在此处查看https://en.wikipedia.org/wiki/List_of_HTTP_status_codes。这是不言自明的。

换句话说,任何代码> = 400(4xx,5xx)都可以视为错误。

您将返回错误消息: "You are not authorized to perform that action"

我要说,这条短信主要对应401/403码。对于5xx错误,我建议您显示一些服务器错误消息。