【发布时间】:2015-10-29 22:52:19
【问题描述】:
我正在尝试调用我的 WebAPI,但我总是收到错误 No Access-Control-Allow-Origin header is present
在Using Cors的文章之后,我们有下面的代码,但它总是落在onerror方法
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'http://localhost:56280/api/Meta/GetListMetas';
var xhr = createCORSRequest('GET', url);
xhr.withCredentials = true;
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function () {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function () {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
我也尝试了JSONP,但又没有成功,落在error 方法
$.ajax({
type: "GET",
dataType: 'jsonp',
url: "http://localhost:56280/api/Meta/GetListMetas"
}).success(function (data) {
alert(data)
}).error(function (da) {
});
WebAPI
我做了一个非常简单的 API 来做示例p>
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
控制器
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class MetaController : ApiController
{
public string GetListMetas()
{
return "1";
}
}
我也尝试序列化返回,但没有成功。
有人可以帮助我吗?
更新
下面,我附上请求头
【问题讨论】:
-
当您调用
api/Meta/GetListMetas时,您是否使用过 Chrome 的开发者工具(或类似的 IE/FF/Safari)来查看您从服务器获得的响应包括标题? -
@tacos_tacos_tacos 我用可以看到标头请求的图像更新了我的问题。
标签: javascript c# asp.net-web-api cors