WebApi を MVC6 にアップグレードしています。
WebApi では、すべての HTTP リクエストをインターセプトでき、それがプリフライトの場合は、ブラウザーが受け入れるヘッダーで応答できました。
MVC6 WebApi で同じことを行う方法を理解しようとしています。
これが WebApi コードです。
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 で同じことを行うにはどうすればよいですか?
ありがとう、ボブ
フィードバックに基づく次の試みは次のとおりです。ミドルウェアのパイプラインを理解していれば、おそらく自分でこれを理解できたでしょう。もちろん今から学びます。
このコードを試してみましたが、期待どおりに http リクエストにヒットしませんでした。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Configure the HTTP request pipeline.
app.UseStaticFiles();
// Add MVC to the request pipeline.
app.UseMvc();
// Add the following route for porting Web API 2 controllers.
// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
// custom middleware to checked each call as it comes in.
app.Use(async (httpContext, next) =>
{
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;
}
await next();
});
}