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?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
RNDThoughts
  • 892
  • 3
  • 13
  • 30
  • Possible duplicate of [How to make CORS Authentication in WebAPI 2?](https://stackoverflow.com/questions/20079813/how-to-make-cors-authentication-in-webapi-2) – Heretic Monkey Jun 27 '17 at 16:52

1 Answers1

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> 
Ionut Ungureanu
  • 1,020
  • 1
  • 13
  • 16
  • 1
    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. – RNDThoughts Jun 29 '17 at 13:27
  • enabling cors in web.config as well as by installing cors package will not work. it will give error _____**** cors enabled multiple times – Heemanshu Bhalla Jan 22 '20 at 05:32
  • i know this answer is more than 2 years old. but still there is something missing in answer to resolve cors issue – Heemanshu Bhalla Jan 22 '20 at 05:38