私のAngularアプリが新しいMVC6 Web Apiと通信できるように、CORSを有効にしようとしています。
CORSプリフライトが最初に送信されるため、「GET」は機能しますが、「POST」は機能しません。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 の実例を持っていますか?
ありがとう