C# asp.net Web API 2 AJAX失败
我使用WebAPI2进行的测试从AJAX失败方法返回状态200 控制器:C# asp.net Web API 2 AJAX失败,c#,asp.net,ajax,asp.net-web-api,C#,Asp.net,Ajax,Asp.net Web Api,我使用WebAPI2进行的测试从AJAX失败方法返回状态200 控制器: [HttpPost] public HttpResponseMessage Post([FromBody] myData m) { return new HttpResponseMessage() { Content = new StringContent("TEST") }; } myData类: public class
[HttpPost]
public HttpResponseMessage Post([FromBody] myData m)
{
return new HttpResponseMessage()
{
Content = new StringContent("TEST")
};
}
myData类:
public class myData
{
public int Id { get; set; }
public string Name { get; set; }
}
从HTML调用帖子:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<script>
var model = {
Name: "Shyju",
Id: 123
};
$.ajax({
type: "POST",
dataType: "text",
data: JSON.stringify(model),
url: "http://localhost:52884/api/contact",
contentType: "application/json",
crossDomain: true,
success: function (response) {
console.log(response)
},
error: function (response) {
console.log("e : " + response)
}
});
</script>
</body>
</html>
var模型={
姓名:“Shyju”,
身份证号码:123
};
$.ajax({
类型:“POST”,
数据类型:“文本”,
数据:JSON.stringify(模型),
url:“http://localhost:52884/api/contact",
contentType:“应用程序/json”,
跨域:是的,
成功:功能(响应){
console.log(响应)
},
错误:函数(响应){
console.log(“e:+响应)
}
});
有人知道它为什么不返回消息“TEST”吗
感谢在web api 2中抛出http异常的好方法:
throw new HttpResponseException(
new HttpResponseMessage
{
StatusCode = HttpStatusCode.InternalServerError,
ReasonPhrase = "Internal Server Error",
Content = new StringContent(JsonConvert.SerializeObject(myobject))
});
然而,值得注意的是,一个简单的throw异常语句会导致500,这也会导致500。在我的示例中,它绕过了错误过滤和我的全局异常处理程序,只向UI返回错误状态代码和一些错误文本。确实如此。使用
res.data
也可以使用然后而不是完成
<代码>完成
接受两个参数,一个解析函数和一个拒绝函数。您试图将解析函数视为数据。请参阅jQuery文档。您是指my console.debug中的res.data吗?但它不会进入“完成”功能。您在哪里将状态代码设置为不为200?我不会设置它。我应该这样做吗?仍然返回相同的问题。如何调试web api?