我正在将我的 WebApi 升级到 MVC6。
在 WebApi 中,我可以拦截每个 HTTP 请求,如果是预检,我可以用浏览器可以接受的 header 进行响应。
我正在尝试找出如何在 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();
});
}
最佳答案
您可以添加自己的 middleware为了那个原因。这是一个将它内联添加的快速示例,但您也可以将其封装在一个类中:
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();
});
您可能还想关注 ongoing work在 ASP 5 框架内支持 cors
关于cors - MVC6 Cors - 拦截预检,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31976337/