问题
I'm upgrading my WebApi(s) to MVC6.
In WebApi I could intercept every HTTP request and if it was a preflight I could respond with headers the browser would accept.
I'm trying to figure out how to do the same thing in MVC6 WebApi.
Here is the WebApi code.
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();
}
}
How do I do the same thing with MVC6?
Thanks, Bob
Here is my next attempt based on feedback. I could probably figure this out on my own if I understood the middleware pipeline. I'll learn it now of course.
I tried this code but it's not hit on http requests as I had hoped.
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();
});
}
回答1:
You can add your own middleware for that. Here is a quick example adding it inline, but you could also encapsulate in a class:
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();
});
You will probably also want to keep an eye on the ongoing work to support cors within the ASP 5 framework
来源:https://stackoverflow.com/questions/31976337/mvc6-cors-intercept-preflight