我試圖使用asp.net的Web API創建一個基本的REST的職位,但它返回的錯誤狀態:0。此外,它看起來像失敗AJAX請求asp.net網頁API AJAX狀態0
我控制器:
[HttpPost]
public myData Post(myData m)
{
return m;
}
我的類:
public class CLData
{
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>
//form encoded data
var dataType = 'application/x-www-form-urlencoded; charset=utf-8';
var data = $('form').serialize();
//JSON data
var dataType = 'application/json; charset=utf-8';
var data = {
FirstName: 'Andrew',
LastName: 'Lock',
Age: 31
}
console.log('Submitting form...');
$.ajax({
type: 'POST',
url: 'http://localhost:52884/api/contact',
dataType: 'json',
contentType: dataType,
data: data,
success: function(result) {
console.log('Data received: ');
console.log(result);
},
error: function(error){
console.log('Error: ');
console.log(error);
}
});
</script>
</body>
</html>
我不知道爲什麼我的控制檯日誌:
Submitting form..
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:52884/api/contact. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Error:
Object with status: 0
有誰知道我做錯了嗎?我只是想學習Web API,這就是爲什麼這個例子很簡單。
就像一個實驗,嘗試用'url:'/ api/contact'替換'url:'http:// localhost:52884/api/contact'。假設您的應用程序實際上承載了API端點和服務頁面。如果它未提供頁面,則需要在應用程序中啓用跨源請求。 –
仍然是同樣的問題。 – user6824563