0

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?

1

1 Answer 1

2

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> 
Sign up to request clarification or add additional context in comments.

3 Comments

It turned out to be a combination of the answer above and the fact that my Visual Studio wasn't compiling my ApiController correctly. It was hitting the controller constructor upon startup but just wouldn't hit my action. I copied the action code to a different controller and it fired correctly. Resolved by deleting the duff controller and creating a new file.
enabling cors in web.config as well as by installing cors package will not work. it will give error _____**** cors enabled multiple times
i know this answer is more than 2 years old. but still there is something missing in answer to resolve cors issue

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.