No Access-Control-Allow-Origin header on the requested resource when invoking WebAPI

I am trying to call my WebAPI but I always get the error No Access-Control-Allow-Origin header is present

Following on Using the Cors article , we have the code below, but it always crashes onerror

method

// 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 tried it too JSONP

, but without success, ended up on the error

method

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

      

WebAPI

I made a pretty simple API to make a sample

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 have tried serializing the return, bu with no success as well.

Can anyone help me?

UPDATE

Below I am attaching the request header

enter image description here

+3


source to share


2 answers


The problem mentioned by Vaughn Okerlund is in the request made by the client.
The request is blocked by the server because it does not recognize the client's request.

You can enable the original whitelist of the domain the client is running on:

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 included the entire query for every verb from this domain:

http://localhost:7185

      



If you customize everything 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 with this syntax:

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

      

+1


source


Searching here , it seems the problem is that in your controller's response to the service request, you are sending a lookup header (*) for origin, rather than specifying a domain to resolve. To send a trusted request, the server must grant access to a specific domain:



Important note: when responding to a trusted request, the server must specify the domain and cannot use wild carding. The above example will fail if the header was wildcard: Access-Control-Allow-Origin: *. Because Access-Control-Allow-Origin explicitly mentions http: //foo.example , credential-dependent content is returned to the calling web content. Notice that there is another cookie set on line 22.

+1


source







All Articles