简体   繁体   English

调用WebAPI时,请求的资源上不存在Access-Control-Allow-Origin标头

[英]No Access-Control-Allow-Origin header is present on the requested resource when calling WebAPI

I'm trying to call my WebAPI, but I'm always get the error No Access-Control-Allow-Origin header is present 我正在尝试调用我的WebAPI,但我总是得到错误No Access-Control-Allow-Origin header is present

Following the Using Cors article, we have the code below, but it always falls onerror method 使用一个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();
}

I've tryied the JSONP also but without success again, falls on error method 我也尝试了JSONP但没有再次成功,落在error方法上

    $.ajax({
        type: "GET",
        dataType: 'jsonp',
        url: "http://localhost:56280/api/Meta/GetListMetas"
    }).success(function (data) {
          alert(data)
    }).error(function (da) {
    });

WebAPI 的WebAPI

I made a pretty simple API to do the sample 我做了一个非常简单的API来做样本

WebApiConfig.cs 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 }
        );
    }
}

Controller 调节器

    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class MetaController : ApiController
    {
        public string GetListMetas()        
        {
           return "1";
        }
    }

I've tryied serialize the return also, bu without success. 我也试过序列化返回,但没有成功。

Someone can help me ? 有人可以帮帮我吗?

UPDATE UPDATE

Below, I attach the request header 下面,我附上请求标题

在此输入图像描述

Looking here , it seems the issue is that in your controller's response to the service's request you're sending the wildcard header (*) for the origin rather than specifying a domain to allow. 在这里看来,问题似乎是在你的控制器对服务请求的响应中你发送了原始的通配符头(*)而不是指定允许的域。 In order to send a credentialed request, the server has to grant access to a specific domain: 为了发送凭证请求,服务器必须授予对特定域的访问权限:

Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding. 重要说明:在响应凭证请求时,服务器必须指定域,并且不能使用通配符。 The above example would fail if the header was wildcarded as: Access-Control-Allow-Origin: *. 如果标头被通配为:Access-Control-Allow-Origin:*,则上述示例将失败。 Since the Access-Control-Allow-Origin explicitly mentions http://foo.example , the credential-cognizant content is returned to the invoking web content. 由于Access-Control-Allow-Origin明确提到了http://foo.example ,因此将凭证识别内容返回到调用Web内容。 Note that in line 22, a further cookie is set. 请注意,在第22行中,设置了另一个cookie。

The problem, as Vaughn Okerlund mentioned, is in the request made by the client. 正如Vaughn Okerlund所提到的那样,问题在于客户提出的要求。
The request is blocked by the server cause it does not recognize the client's request. 该请求被服务器阻止,因为它无法识别客户端的请求。

You can enabled the origin white-listing the domain where the client is running: 您可以启用原始白名单列出运行客户端的域:

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 }
    );
}

As you can see I've enabled all the request for every verb from this domain: 正如您所看到的,我已为此域中的每个动词启用了所有请求:

http://localhost:7185

If you configure everything there you don't need 如果你在那里配置你不需要的东西

[EnableCors(origins: "*", headers: "*", methods: "*")]

on your controller. 在你的控制器上。

Considering your client is hosted in http://localhost:7185/ you can use jQuery to call the server simply using this syntax: 考虑到您的客户端托管在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);
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript-所请求的资源上没有“ Access-Control-Allow-Origin”标头 - Javascript - No 'Access-Control-Allow-Origin' header is present on the requested resource 请求的资源上不存在“Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource 角度4-所请求的资源上没有“ Access-Control-Allow-Origin”标头 - Angular 4 - No 'Access-Control-Allow-Origin' header is present on the requested resource NodeJ在所请求的资源上不存在“ Access-Control-Allow-Origin”标头 - NodeJs No 'Access-Control-Allow-Origin' header is present on the requested resource Access-Control-Allow-Origin header 存在于请求的资源上 - Access-Control-Allow-Origin header is present on the requested resource 请求的资源 .htaccess 上不存在 Access-Control-Allow-Origin 标头 - No Access-Control-Allow-Origin header is present on the requested resource .htaccess XMLHttpRequest请求的资源上没有“Access-Control-Allow-Origin”标头 - XMLHttpRequest No 'Access-Control-Allow-Origin' header is present on the requested resource 请求的资源上不存在Access-Control-Allow-Origin标头 - Access-Control-Allow-Origin header is not present on the requested resource 请求的资源上不存在Access-Control-Allow-Origin标头 - No Access-Control-Allow-Origin header is present on the requested resource 请求的资源 nodejs 上不存在“Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource nodejs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM