One one of my ASP.NET Web API controllers. I am getting the following error returned on my client application:
Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:8100' is therefore not allowed access.
I recognise that this error occurs because the header contains multiple values. I can see this in the 'Response Headers' when the call is made to the API via Chrome, it looks like this:
HTTP/1.1 200 OK
Cache-Control: no-cache
Content-Length: 0
Server: Microsoft-IIS/8.0
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, Accept, Pragma, Cache-Control, Authorization
Access-Control-Max-Age: 1728000
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Set-Cookie: ARRAffinity=ef9b3770b61f10f9696b0dedcb39a7f47a83c0e4d6cdbf367f3149482592ef06;Path=/;HttpOnly;Domain=seirse.azurewebsites.net
As you can see, it's clearly there twice.
The problem I have is that the only place I have enabled CORS is via the web.config in my application, e.g.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />
</customHeaders>
</httpProtocol>
I have made 100% sure that I have not enabled CORS via Startup.cs nor in the controller either.
There is nothing out of the ordinary with the controller as far as I can see:
// GET: api/Address/all
[HttpGet]
public AddressResultModel All()
{
try
{
var userId = _accountService.GetUserId(Request);
return _customerRepository.GetAddresses(userId);
}
catch (Exception)
{
return null;
}
}
Any ideas what the problem might be?
It turned out I had code inside my Global.asax.cs which was adding headers to the response for OPTIONS HTTP requests.
The reason I added this code was due to a separate issue whereby I was getting a "405 Method Not Allowed" error message for OPTIONS HTTP requests.
To fix both issues, I removed the code which was adding the extra headers and trimmed it down to this:
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin", StringComparer.CurrentCultureIgnoreCase)
&& Request.HttpMethod == "OPTIONS")
{
Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");
Response.End();
}
}
I'm not sure why this fixed the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With