The problem:
For some reason, when enabling CORS, the Access-Control-Allow-Origin
header is not included in the response.
The error:
Access to XMLHttpRequest at 'https://.../api/endpoints/some-path' from origin 'https://some.site.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Configuration (.NET MVC 5)
web.config headers:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Web API config:
config.EnableCors();
API endpoint:
[RoutePrefix("api/endpoints")]
[EnableCors(origins: "https://some.site.com", headers: "*", methods: "*")]
public class MyApiController : ApiController
{
[HttpPost]
[Route("some-path")]
[EnableCors(origins: "https://some.site.com", headers: "*", methods: "*")]
public ResponseModel GetSomeResponse(DataModel model) { ... }
}
global.asax.cs
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
HttpContext.Current.Response.Flush();
}
The only way I can get successfully get the application to return that header is to explicitly include it as a custom header in the web.config:
<add name="Access-Control-Allow-Origin" value="https://some.site.com" />