I'm trying to enable CORS allowing my angular app to talk to a new MVC6 Web Api.
The "GET" works but "POST" will not because a CORS Preflight is sent first. IIS intercepts this preflight and responds.
In WebApi2 I could stop IIS from intercepting the preflight with the following web.config setting.
<configuration>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET, HEAD, POST, DEBUG, DELETE, PUT, PATCH, OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</configuration>
Then I could interrogate the request and return the headers I wanted for "OPTIONS".
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Context.Request.Path.Contains("api/") && Context.Request.HttpMethod == "OPTIONS")
{
Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
Context.Response.End();
}
}
I'm able to do both of these in the new MVC6 WebApi but for some reason I can't get IIS to stop intercepting the "OPTIONS" preflight.
I'm using this code in the MVC and I believe it works if I can only get IIS to stop intercepting the "OPTIONS" request.
app.Use(async (httpContext, next) =>
{
httpContext.Response.OnSendingHeaders((state) =>
{
if (httpContext.Request.Path.Value.Contains("api/") && httpContext.Request.Method == "OPTIONS")
{
httpContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { httpContext.Request.Headers["Origin"] });
httpContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });
httpContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
httpContext.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
return;
}
}, null);
await next();
});
Has anyone dealt with this or have a working example of MVC6 with CORS working?