【发布时间】:2018-03-25 20:55:42
【问题描述】:
我使用 ASP.NET Web API 的 HttpPost 总是从 AJAX 请求返回错误。
我的控制器:
public class ContactController : ApiController
{
[HttpPost]
[EnableCors(origins: "http://localhost:52884", headers: "*", methods: "*")]
public string Post(myData m)
{
return String.Format("{0} {1:d}", m.FirstName, m.LastName);
}
}
我的班级:
public class myData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
我的 HTML 请求:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<script>
$.ajax(
{
url: "http://localhost:52884/api/contact",
type: "POST",
dataType: 'json',
data: { FirstName: "FName", LastName: "LName" },
success: function (result) {
alert(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).message;
alert(err);
}
});
</script>
</body>
</html>
当我在浏览器上运行它时,我收到警告:错误错误。
有谁知道我做错了什么?
如果我使用 Postman 运行它,它可以工作。但我在 Ajax 请求中需要它,因为其他网站会调用我的 API
【问题讨论】:
-
首先,URL 应该是
/api/contact,其次是在模型中传递名称为myData的数据 -
谢谢。是的,模型中的数据是 myData。我这里贴错了。我把网址改成了/api/contact,还是一样的问题
-
我不知道为什么,但是我将 jsonp 添加到了我的 dataType 中,它给了我错误:Loading failed for the
标签: c# asp.net ajax asp.net-web-api