Sta*_*ams 5 asp.net-mvc jquery ios angularjs asp.net-mvc-5
考虑以下控制器操作,网络上存在大量示例:
public ActionResult Fail()
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "My helpful message");
}
Run Code Online (Sandbox Code Playgroud)
现在,我们将通过 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>
Run Code Online (Sandbox Code Playgroud)
当我在 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
});
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
您可以依赖从服务器返回的状态代码结果(至少在 IIS 上)。
但是,不能保证浏览器将支持它。
但是您的断言是正确的,您应该使用模型返回任何错误以显示在客户端上以获得一致的结果。
| 归档时间: |
|
| 查看次数: |
1134 次 |
| 最近记录: |