MB34 MB34 - 2 months ago 5x
C# Question

Cors issues on WebAPI

Enabling Cors on WebAPI

I have this set in WebApiConfig.cs


and this is how my attribute is setup for my controller method:

[EnableCors("http://dev.example.com,http://personal.example.com,http://www.example.com", // Origin
"Accept, Origin, Content-Type, Options", // Request headers
"POST", // HTTP methods
PreflightMaxAge = 600 // Preflight cache duration

But I still get the error: "The 'Access-Control-Allow-Origin' header contains multiple values."

What else do I need to do to prevent this? We must allow from all three domains. but the first 2 are sub-domains of the last one.


do you have any options set into your web.config file for cors ? i.e something like <add name="Access-Control-Allow-Origin" value="*"/>

if yes make sure to remove that, and control the cors through the code only.

Edit: well, that means that you always add the header to your response, no matter which controller the request hits, and in case the request hits the controller with the EnableCors attribute it will add another header. If you removed the one in the Application_BeginRequest() it should work, however that means that you need to decorate all other controllers with EnableCors attribute, which maybe acceptable in your case, otherwise, you need to add a DelegateHandler where you can check the request and set the cors depending on the requested controller. have a look at this http://georgedurzi.com/implementing-cross-browser-cors-support-for-asp-net-web-api/ it may help start with DelegateHandlers. Hope that helps.