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?

1

1 Answer 1

0

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

[EnableCors("*", "*", "*")] 
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.