我尝试启用CORS,允许我的角度应用与新的MVC6 Web Api对话。
" GET"工作,但" POST"不会因为首先发送CORS预检。 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>
然后我可以插入请求并返回我想要的标题&#34; OPTIONS&#34;。
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停止拦截&#34; OPTIONS&#34;预检。
我在MVC中使用此代码,我相信如果我只能让IIS停止拦截&#34; OPTIONS&#34;请求。
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的工作示例?
由于
答案 0 :(得分:1)
我建议一个正常工作:
app.Use(async (context, next) =>
{
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type, x-xsrf-token" });
if (context.Request.Method == "OPTIONS")
{
context.Response.StatusCode = 200;
}
else
{
await next();
}
});