HttpStatusCodeResult.StatusDescription的可靠性如何?

时间:2015-08-30 01:20:14

标签: jquery ios angularjs asp.net-mvc asp.net-mvc-5

考虑以下控制器操作,其中存在大量示例:

public ActionResult Fail()
{
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "My helpful message");
}

现在,我们将通过Ajax调用该操作并在页面中显示结果;

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript">
            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    document.body.innerHTML = xmlhttp.response;
                }
            }

            xmlhttp.open("POST", "/log/fail", true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.send();

        </script>
    </head>
    <body>
    </body>
</html>

当我在Windows 10设备上按Chrome或Firefox打开该页面时,我会收到一个完整的错误报告,其中显示我的有用信息

然而,当我在iOS设备上打开此页面(使用iPad Air,iPhone 5S测试)时,收到的回复中没有任何消息。

这让我相信您不能依赖HttpStatusCodeResult.StatusDescription将其返回给客户端而不是检测应用程序问题并使用new HttpStatusCodeResult()进行响应,而是将模型发回应扩展到前端以包括任何特定于应用程序的错误消息并正常发回(HttpStatusCode.OK)。是这种情况吗?

请注意,这扩展到我最初找到它的AngularJs,以及jQuery;

AngularJS

$http.post('/log/fail')
    .then(function (response) {
        // successful
    }, function (response) {
        document.body.innerHTML = response.statusText; // 'Bad Request' in iOS
    });

的jQuery

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script type="text/javascript">
            $.ajax({ url: '/log/fail', method:'POST' }).error(function (response) {
                document.body.innerHTML = response.statusText; // 'Bad request' in iOS
            });
        </script>
    </head>
    <body>
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

可以依赖于从服务器返回的状态代码结果(至少在IIS上)。

但是,无法保证浏览器会支持它。

但是你的断言是正确的,你应该使用模型返回任何错误,以便在客户端上显示以获得一致的结果。

相关问题