Javascript 调用WebAPI时,请求的资源上不存在访问控制允许源标题

Javascript 调用WebAPI时,请求的资源上不存在访问控制允许源标题,javascript,c#,asp.net-web-api,cors,Javascript,C#,Asp.net Web Api,Cors,我正在尝试调用我的WebAPI,但我总是得到错误不存在访问控制允许源站标题 在本文之后,我们有下面的代码,但它总是落在错误的方法上 // Create the XHR object. function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // XHR for Chrome/Firefox/Opera/Safa

我正在尝试调用我的WebAPI,但我总是得到错误
不存在访问控制允许源站标题

在本文之后,我们有下面的代码,但它总是落在错误的方法上

// 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();
}
    $.ajax({
        type: "GET",
        dataType: 'jsonp',
        url: "http://localhost:56280/api/Meta/GetListMetas"
    }).success(function (data) {
          alert(data)
    }).error(function (da) {
    });
WebAPI

我制作了一个非常简单的API来完成这个示例

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";
        }
    }
我也试着连载返回,但没有成功

有人能帮我吗

更新

下面,我附上请求标题

看,问题似乎在于,在控制器对服务请求的响应中,您发送的是源站的通配符标头(*),而不是指定要允许的域。为了发送认证请求,服务器必须授予对特定域的访问权限:

重要注意事项:当响应认证请求时,服务器必须指定域,并且不能使用通配符。如果标题通配符为:Access Control Allow Origin:*,则上述示例将失败。由于访问控制Allow Origin显式地提到,凭证识别内容将返回给调用web内容。注意,在第22行中,设置了另一个cookie

如前所述,问题在于客户提出的请求。
该请求被服务器阻止,因为它无法识别客户端的请求

您可以在源代码中显示运行客户端的域:

public static void Register(HttpConfiguration config)
{
    var corsAttr = new System.Web.Http.Cors.EnableCorsAttribute("http://localhost:7185", "*", "*");
    config.EnableCors(corsAttr);

    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}
如您所见,我已启用此域中每个动词的所有请求:

http://localhost:7185
如果您在那里配置了您不需要的所有内容

[EnableCors(origins: "*", headers: "*", methods: "*")]
在你的控制器上

考虑到您的客户托管在
http://localhost:7185/
您可以使用jQuery调用服务器,只需使用以下语法:

$.ajax({
    type: 'GET',
    url: 'http://localhost:56280/api/Meta/GetListMetas',
    data: {},
    dataType: "json",
    // crossDomain: true,
    success: function (result) {
        alert(result);
    },
    //complete: function (jqXHR, textStatus) {
    //},
    error: function (req, status, error) {
        alert(error);
    }
});

当你调用
api/Meta/GetListMetas
时,你是否使用Chrome的开发工具(或IE/FF/Safari的类似工具)来查看服务器的响应,包括标题?@tacos_tacos_tacos_tacos我用一个可以看到标题请求的图像更新了我的问题。@VaughnOkerlung在你的回答中,我看到了一些奇怪的事情,通过onLoad方法,它工作良好。