【发布时间】:2013-11-07 23:29:19
【问题描述】:
我正在从服务器调用一个方法,该方法返回一个错误响应,例如(400 和 500 个错误),但我的 AngularJS 错误回调没有被调用,并且即使我的状态代码包含 400 或 500,也总是调用成功回调。有人可以告诉我我做错了什么吗?请参阅下面的 Angular 和 WebAPI 代码:
AngularJS 代码:
$http.get("/api/employee")
.success(function (data, status, headers, config) {
console.log(data);
return data;
}).error(function (data, status, headers, config) {
alert("error");
return status;
});
Web API 代码:
public HttpResponseMessage Get(EmployeeModel employee)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
//some other code
}
【问题讨论】:
-
你能在浏览器网络选项卡中查看响应状态吗
-
您的 JavaScript 正在调用
GET,但您发布了PUT的代码。使用浏览器调试工具或 Fiddler 看看发生了什么。 -
抱歉打错了。此外,这就是我得到的响应:HTTP/1.1 400 Bad Request Cache-Control: no-cache Pragma: no-cache Expires: -1 Server: Microsoft-IIS/8.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?RDpcU2hhblxDb25zdHJ1Y3Rpb25XZWJBcGlcQ29uc3RydWN0aW9uV2ViQXBpXGFwaVxzdXBwbGllcg==?= X-Powered-By: ASP.NET Date: Tue, 29 Oct 29 21:21:18 GMT Content-Length:
-
您使用的是哪个 AngularJS 版本? AngularJS 1.2 版存在问题。[*|rc] 版本。您可以升级到最新的 stable(1.2.9) 版本,它会正常工作。