我知道这是个老生常谈的问题,我看过很多关于这个问题的文章,最后终于讲到这里。没有身份验证(没有System.Web.Mvc.Authorize),每件事情都能正常工作:
但是,当授权被添加到api控制器时,一切都会出错。
这里的网页调用api,有多达7种解决方案,我从网络上读到,将是一本教科书,如果其中任何一个有效的话。许多人说“它对我有用”,但对我来说没有。
我在标题下注释了所有的解决方案,并记录了它所造成的错误。
var host = 'http://localhost:54364/api/products/';
userName = "name@domain.com";
password = "password";
$(document).ready(function () {
//Solution 1: OPTIONS http://localhost:54364/api/products/GetAllNames?name=someone 405 (Method Not Allowed) / http://localhost:54364/api/products/GetAllNames?name=someone. Invalid HTTP status code 405
//$.ajaxSetup({
// headers: {
// 'Authorization': "Basic " + btoa("cheny@cheny.com" + ":" + "nodenode")
// }
//});
$.ajax({
type: "GET",
url: host + "GetAllNames",
dataType: 'json',
//Solution 2: Ok, but User.Identity.UserName returns "", an empty string; I think it does not work at all.
//username: userName,
//password: password,
async: false,
//Solution 3: GET http://localhost:54364/api/products/GetAllNames?name=someone 405 (Method Not Allowed) / OPTIONS http://localhost:54364/api/products/GetAllNames?name=someone 405 (Method Not Allowed) / XMLHttpRequest cannot load http://localhost:54364/api/products/GetAllNames?name=someone. Invalid HTTP status code 405
//headers: { "Authorization": btoa("Basic " + userName + ":" + password) },
//Solution 4: XMLHttpRequest cannot load http://localhost:54364/api/products/GetAllNames. Wildcards cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:64710' is therefore not allowed access.
//xhrFields: {
// withCredentials: true
//},
beforeSend: function (xhr) {
//Solution 5: Same with solution 2.
//xhr.withCredentials = true;
//Solution 6: OPTIONS http://localhost:54364/api/products/GetAllNames?name=someone 405 (Method Not Allowed) / OPTIONS http://localhost:54364/api/products/GetAllNames?name=someone 405 (Method Not Allowed) / XMLHttpRequest cannot load http://localhost:54364/api/products/GetAllNames?name=someone. Invalid HTTP status code 405
//xhr.setRequestHeader("Authorization", "Basic " + btoa(userName + ":" + password));
//Solution 7 ( 5 + 6 ): same with solution 6.
},
crossDomain: true,
success:
function(data) {
// On success, 'data' contains a list of products.
$.each(data, function(key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#ajax'));
});
}
});对于ajax和web (只有2天的经验),我想我可能错过了一些东西,例如,解决方案4没有用户名/密码信息,它怎么能工作呢?
谢谢您,欢迎您提出任何意见。
发布于 2014-04-03 06:44:57
问题是您的响应的Access-Control-Allow-Origin头。如果使用的是身份验证,则不能使用通配符*。您需要显式地设置域。
如果您想使用withCredentials: true,那么服务器必须将额外的头Access-Control-Allow-Credentials设置为true。
Access-Control-Allow-Credentials: truehttps://stackoverflow.com/questions/21432371
复制相似问题