RNDThoughts
RNDThoughts

Reputation: 1004

Unable to enable CORS in WebAPI 2

This is driving me nuts and I apologise if it's a duplicate but I've read through all the other WebAPI/CORS questions and can't find any configuration that works.

I have a WebAPI 2 project on .NET 4.6.1 which runs perfectly - controllers all initialise etc, etc. I can call the different actions directly and all is fine.

However, when I try to call the API from another website I know I need to use CORS to enable this otherwise i get the 500 server error / pre-flight errors.

So I installed System.Web.Http.Cors and did this as instructed in my WebApiConfig:

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
app.UseWebApi(config);

I would expect all ApiControllers and actions to respond to an OPTIONS request. I can see my ajax request making the OPTIONS request but I get an internal server error from WebAPI:

Request URL:http://localhost:55579/api/event?start=2017-06-01&end=2017-06-30
Request Method:OPTIONS
Status Code:500 Internal Server Error
Remote Address:[::1]:55579
Referrer Policy:no-referrer-when-downgrade

...and making a direct OPTIONS call via Postman gives me:

{
    "$id": "1",
    "message": "The requested resource does not support http method 'OPTIONS'."
}

I have also tried adding the attribute to my controller but this has no effect either.

[RoutePrefix("api/event")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class EventController : ApiController

What am I missing here?

Upvotes: 0

Views: 3261

Answers (1)

Ionut Ungureanu
Ionut Ungureanu

Reputation: 1030

you also need to add the appropriate http headers in your web.config:

<system.webServer>
  <httpProtocol>
    <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
       <add name="Access-Control-Allow-Methods" value="*" />
    </customHeaders>
  </httpProtocol> 

Upvotes: 2

Related Questions