1

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.

enter image description here

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

3
  • The error is probably something configuration related. How is your routing set up? Can you see errors on the server? Commented Mar 5, 2016 at 1:18
  • @Irb I got it set up pretty simple, I've added the whole Register method to the question, apart from that I don't have any filters or other config for the Api, that method is the only thing called in Global.asax. As for errors I dont see any errors. The controller method runs through fine from the break point's i've put on it Commented Mar 5, 2016 at 1:24
  • Possible duplicate of c# Web Api with CORS Enabled and the dreaded No 'Access-Control-Allow-Origin' header is present on the requested resource Commented Mar 5, 2016 at 1:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.