3

我正在将我的 WebApi(s) 升级到 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();
        });

    }
4

1 回答 1

3

您可以为此添加自己的中间件。这是一个内联添加它的快速示例,但您也可以封装在一个类中:

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();
});

您可能还需要密切关注在ASP 5 框架内支持 cors的正在进行的工作

于 2015-08-13T08:23:55.163 回答