2016-12-11 35 views
0

我有一個簡單的ASP.NET Web API應用程序,具有單獨的帳戶進行身份驗證。jQuery + ASP.NET Web API + CORS錯誤

我啓用CORS它:安裝包,並補充說:

var cors = new EnableCorsAttribute(
     origins: "*", 
     headers: "*", 
     methods: "*"); 
     config.EnableCors(cors); 

到文件WebApiConfig

現在,我想使用jQuery從簡單的網頁發出請求。我現在有這樣的代碼:

var loginData = { 
    grant_type: "password", 
    username: "foo", 
    password: "Something_1562" 
}; 

$.ajax({ 
    type: 'POST', 
    url: "https://localhost:44351/Token", 
    data: loginData 
}).done(function (data) { 
    alert(data.userName); 
    alert(data.access_token); 

}).fail(function (data) { 
    alert('Request Status: ' + req.status + ' Status Text: ' + req.statusText + ' ' + req.responseText); 
}); 

而且我得到這個:

XMLHttpRequest cannot load https://localhost:44351/Token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

編輯:

一些額外的信息: - 我有HTTPS/SSL啓用的網絡API - 的API is is on ISS Express

回答

1

我希望以下幾點&鏈接有用:

Access-Control-Allow-Origin: * 

"*"的值的特殊之處在於它不允許請求提供憑證,即HTTP認證,客戶端SSL證書,也不允許發送Cookie。來源:Wikipedia

因此你的Web API需要指定URL是使用AJAX訪問它。例如。

[EnableCors(origins: "http://yourAjaxClientURL", headers: "*", 
    methods: "*", SupportsCredentials = true)] 

要允許在網頁API跨來源憑證,設置SupportsCredentials屬性true[EnableCors]屬性。來源:Enabling Cross-Origin Requests in ASP.NET Web API 2

第三有用的鏈接www.w3.org - cors

+0

這奏效了!謝謝。 –

+0

順便說一句,我現在有一個不同的問題:我的GET請求正在更改爲選項,結果405代碼。我已閱讀了一些帖子,但沒有任何作品...任何提示? –

+0

@CátiaAzevedo也說不定這些鏈接也有幫助:http://enable-cors.org/server_iis7.html 和http://stackoverflow.com/questions/28488535/cors-settings-for-iis-7-5 – jyrkim