我正在尝试启用 CORS,以允许我的 Angular 应用程序与新的 MVC6 Web Api 对话。
“GET”有效,但“POST”无效,因为首先发送了 CORS Preflight。IIS 拦截此预检并做出响应。
在 WebApi2 中,我能够通过以下 web.config 设置阻止 IIS 拦截预检。
<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>
然后我可以询问请求并返回我想要的“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();
}
}
我可以在新的 MVC6 WebApi 中完成这两项工作,但由于某种原因,我无法让 IIS 停止拦截“OPTIONS”预检。
我在 MVC 中使用这段代码,我相信如果我只能让 IIS 停止拦截“OPTIONS”请求,它就可以工作。
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();
});
有没有人处理过这个问题或者有一个使用 CORS 的 MVC6 的工作示例?
谢谢