简体   繁体   中英

CORS Error when trying to return an Object from asp.net Web API 2 to Angular Front end

So I have two projects, one is the asp.net Web API2 and the other is the Angular 1.5 Client side. I'm starting pretty simple, just returning a list of objects but when I try this I always get the error No 'Access-Control-Allow-Origin' header is present on the requested resource. which is very confusing to me since if I return a list of strings I do not get this error and the data loads fine.
Here is my angular call:

$http.get("http://localhost:53574/api/ReturnStringList")
    .then(function(response) {
    //success
    console.log(response.data);
    angular.copy(response.data, vm.links);
    }, function (error) {
    //failure
    vm.errorMessage = "Failed to load data";
    });

Web API Controller Methods

// GET api/DataController
[HttpGet]
public IEnumerable<string> Get()
{
    var stringList= db.Links.Take(10).Select(x => x.LinkString).ToList();
    return stringList;
}
// GET api/DataController/5
[HttpGet]
public IEnumerable<Link> Get(string id)
{
    var links = db.Links.Take(10).ToList();

    return links;
}

My Web API's config file: WebApiConfig

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services


        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        var cors = new EnableCorsAttribute("*", "*", "GET, POST");
        config.EnableCors(cors);

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

So if I change the get URL to be api/ReturnStringList it'll return the list of strings fine but it i then go to api/ReturnStringList/5 it will return the error below without me changing anything else.

在此处输入图片说明

I've inspected the Response and I can see that the header is not there on the failed case but is clearly there on the succeeding one, yet I do not understand why this is happening.

Edit : I've looked through the other topic suggested by @Jim G but did not solve it. I am using that NuGet Package suggested and I have adjusted my config ordering as noticed without change

**Update: ** I found that there was something going wrong on the server, after working with fiddler for a bit I found that the object wasn't being serialized properly. After adding GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; it's working fine

Believe you need to add the OPTIONS method to your CorsEnableAttribute.

 var cors = new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS");

You'll note an Options call goes out before the Get request to do some pre-flight sniffing. If you don't support the method, the CORS can't work. From Mozilla's write up on CORS

the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM