2

I have a strange issue that I have not been able to find an answer for.

I have used CORS many times in my Web API applications to allow cross-origin requests from client apps without seeing this problem.

In my WebApiConfig class I have:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

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

        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);            
    }
}

I have three controller methods with attribute routing:

[HttpPost]
[Route("pedigree")]
public IHttpActionResult GetPedigree([FromBody]Input input)
{
    // some stuff    
    return Ok(result);
}

[HttpPost]
[Route("descendants")]
public IHttpActionResult GetDescendants([FromBody]Input input)
{
    // some stuff           
    return Ok(result);
}

[HttpPost]
[Route("relatives")]
public IHttpActionResult GetRelatives([FromBody]Input input)
{
    // some stuff            
    return Ok(person);
}

The first two methods work fine and return data. The third one does not, it fails CORS with:

XMLHttpRequest cannot load http://localhost:21870/api/familysearch/relatives. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500.

I am simply making an ajax request from angular for all three methods:

$http.post('http://localhost:21870/api/familysearch/relatives', postData)
    .then(function (response) {
        // do something
    }).catch(function (e) {
        // do something
    });

Anyone have any ideas?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Starscream1984
  • 3,072
  • 1
  • 19
  • 27
  • Maybe this helps: https://stackoverflow.com/questions/18619656/enable-cors-in-web-api-2. If you have already solved it, please, explain how you did it. – Carlos Feb 06 '19 at 11:31

1 Answers1

0

You need to add EnableCors attribute over your controller class, to enable CORS over that particular WebAPI Controller.

[EnableCors("*", "*", "*")]
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Thanks for your input, I did try that, but no difference. The enablecors in my webapiconfig should be global across all controllers and methods anyway. – Starscream1984 Jun 15 '16 at 12:18