我試圖從JS/Ajax向我的WebAPI發出請求時遇到問題。在我的解決方案中,我有一個在srv02:2400上發佈的Web API和在srv02上發佈的我的網站:2300如何允許CORS for ASP.NET
當我導航到頁面http://srv02:2300/all-requests.aspx時,頁面加載正常,除了應該發送的數據形成我的API
,我得到的錯誤:
XMLHttpRequest cannot load http://srv02:2400/api/requests/find/1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://srv02:2300' is therefore not allowed access. The response had HTTP status code 400.
但是,如果我把網址http://srv02:2400/api/requests/find/1並粘貼到瀏覽器中,它讓我正確的JSON清單!
我試圖在全球範圍內啓用CORS的建議here在我的API是:
- 安裝包Microsoft.AspNet.WebApi.Cors
由addding以下更新我的WebApiConfig.cs :
var cors = new EnableCorsAttribute(「http://srv02:2400」,「」,「」); config.EnableCors(cors);
但是,這沒有奏效。
正如我前面提到的,我做我的請求作爲阿賈克斯多個請求
$.ajax({
url: "http://srv02:2400/api/requests/find/" + id,
type: "GET",
dataType: 'json',
contentType: 'application/json',
success: function (requests) {
console.log('success');
},
error: function (err) {
if (err) {
console.log(err);
}
}
});
我試圖改變JSON來JSONP作爲建議here,但沒有奏效。
任何有關如何解決問題的想法。
謝謝!
哦..我的壞..這是正確的 – Riad
謝謝盧克! – Riad
@riad沒問題 –