I have an ASP.NET web API that is called by three different SPAs. I am using Windows authentication for the web API. First I tried to configure CORS in Web.config as follows:
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="http://localhost:63342" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" /> <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" /> <add name="Access-Control-Allow-Credentials" value="true" /> </customHeaders> </httpProtocol>
This caused a problem before flying:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin (...) is therefore not allowed access.
which I solved by adding the following method to Global.asax.cs:
protected void Application_BeginRequest() { if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS") { Response.Flush(); } }
This approach worked great for a single spa. I thought I could go to Web.config and add another origin as follows:
<add name="Access-Control-Allow-Origin" value="http://localhost:63342,http://localhost:63347,http://localhost:63345/>
but apparently this is unacceptable. This caused the following error:
The 'Access-Control-Allow-Origin' header contains multiple values (...), but only one is allowed. Origin (...) is therefore not allowed access.
So, to fix this, I changed my approach and instead decided to try setting CORS to WebAPIConfig.cs in the Register method, for example:
var cors = new EnableCorsAttribute("http://localhost:63342,http://localhost:63347,http://localhost:63345", "Origin, X-Requested-With, Content-Type, Accept", "GET, POST, PUT, DELETE"); cors.SupportsCredentials = true; config.EnableCors(cors);
I thought this would work, but now I have an error before flying when using PUT and DELETE requests, and I don’t know how to fix it. I debugged the Application_BeginRequest method and it still clears the OPTIONS request, so I don't know what causes this error. Does anyone know how I can solve this problem?
EDIT:
Print preflight error:
