简体   繁体   English

为ASP.NET Core MVC中的所有响应添加标头

[英]Add a header to all responses in ASP.NET Core MVC

I would like to know how I can add Access-Control-Allow-Origin:* to my headers. 我想知道如何在我的标题中添加Access-Control-Allow-Origin:*

I've tried this unsuccessfully: 我试过这个失败了:

app.Use((context, next) =>
{
    context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
    return next.Invoke();
});

Using app.use(...) and mutating context.Response.Headers from within Startup.Configure is correct, but it's important to do it at the right point in the chain. 使用app.use(...)并在Startup.Configure改变context.Response.Headers是正确的,但是在链中的正确位置执行它是很重要的。 ASP.NET Core middleware components can "short-circuit" (see the ASP.NET Core Middleware docs), preventing further middleware from being called, and by experimenting with it I've inferred that UseMvc() does so. ASP.NET核心中间件组件可以“短路”(参见ASP.NET核心中间件文档),防止进一步调用中间件,并通过试验它我推断出UseMvc()这样做。 In an MVC application, then, this means you have to put your app.use(...) call before app.UseMvc() . 在MVC应用程序中,这意味着您必须 app.UseMvc() 之前调用app.use(...) app.UseMvc()

In other words, starting from the template ASP.NET Core 2.0 application that Visual Studio generates for you, you want to modify Startup.Configure in Startup.cs to look something like this: 换句话说,从Visual Studio为您生成的模板ASP.NET Core 2.0应用程序开始,您希望修改Startup.Configure中的Startup.cs ,如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // Add header:
    app.Use((context, next) =>
    {
        context.Response.Headers["Access-Control-Allow-Origin"] = "*";
        return next.Invoke();
    });

    app.UseMvc();
}

You can also try to use the in built CORS Middleware in the asp.net core framework rather than creating your own Middleware. 您还可以尝试在asp.net核心框架中使用内置的CORS中间件 ,而不是创建自己的中间件。

In Configure method of the Startup class add the following code. Startup类的Configure方法中,添加以下代码。

// Add CORS for YourAnotherSite
    app.UseCors(builder =>
       builder.WithOrigins("http://YourAnotherSite.com"));

OR 要么

Use Named Policies 使用命名策略

In Configure method of the Startup class Startup类的Configure方法中

options.AddPolicy("AllowMyOrigin",
        builder => builder.WithOrigins("http://YourAnotherSite.com"));

and then in the ConfigureServices method of the startup class. 然后在启动类的ConfigureServices方法中。

app.UseCors("AllowMyOrigin");

Alternatively, the Policy can be applied at each Controller or Action methods. 或者,可以在每个ControllerAction方法中应用该策略。

We've found the ApplicationBuilder methods inconsistent too - it's not clear when the handler is handing back to the chain (for instance UseStaticFiles() ) and when it's not ( UseMvc() ). 我们发现ApplicationBuilder方法也不一致 - 当处理程序返回链(例如UseStaticFiles() )以及何时不处理( UseMvc() )时, UseMvc()

You don't say what environment you're running under, but if you're intending on using IIS then don't give up on web.config yet! 你没有说你正在运行什么环境,但如果你打算使用IIS,那么就不要放弃web.config了! The url rewrite module works perfectly well, and allows you to set outbound rules on all request. url rewrite模块运行良好,允许您在所有请求上设置出站规则。

There's a good answer here: https://stackoverflow.com/a/26545975/548664 这里有一个很好的答案: https//stackoverflow.com/a/26545975/548664

I tried your code, and it worked beautifully... Placement is key: I'm pretty sure it needs to be early in the chain. 我尝试了你的代码,它工作得很漂亮......安置是关键:我很确定它需要在链条的早期。

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        //app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
        app.Use((context, next) => {
            context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            return next.Invoke();
        });
        app.UseMvc();
        app.UseWebSockets();
        app.UseSignalR();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM