我的asp.net HttpPost測試applicantion在Postman中工作正常,但它在HTML AJAX請求中返回錯誤。asp.net webapi開機自檢郵遞員,但沒有在瀏覽器AJAX請求
我的控制器:
public class ContactController : ApiController
{
[HttpPost]
public string Post([FromBody] myData m)
{
return String.Format("Test A");
}
}
類:
public class myData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
如果我運行的URL郵差請求:http://localhost:52884/api/contact和身體:
{
"FirstName" : "FName",
"LastName" : "LName"
}
它運行良好!我看到輸出: 「測試A」
然而,當我嘗試它與HTML Ajax請求:
<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: 'jsonp',
data: { FirstName: "FName", LastName: "LName" },
success: function (result) {
alert(result);
},
error: function (xhr, status, p3, p4) {
console.debug(xhr);
var err = "Error " + " " + status + " " + p3;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).message;
alert(err);
}
});
</script>
</body>
</html>
我在控制檯中看到的錯誤:
The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol
Loading failed for the <script> with source 「http://localhost:52884/api/contact?callback=jQuery112409902197956907268_1507917530625&FirstName=FName&LastName=LName&_=1507917530626」.
請將**'dataType:'jsonp'' **更改爲**'dataType:「json」'**。 –
您正在使用jsonp,但在您的代碼中沒有回調。您是否嘗試過使用'JSON.stringyfy({名字:「FName」,姓氏:「LName」})' – Niladri
您使用的是哪種版本的web api?你有沒有在配置文件中設置json格式的默認返回值? – Niladri