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

21,590

Solution 1

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. 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. In an MVC application, then, this means you have to put your app.use(...) call before 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:

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

Solution 2

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

Solution 3

You can also try to use the in built CORS Middleware in the asp.net core framework rather than creating your own Middleware.

In Configure method of the Startup class add the following code.

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

OR

Use Named Policies

In Configure method of the Startup class

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

and then in the ConfigureServices method of the startup class.

app.UseCors("AllowMyOrigin");

Alternatively, the Policy can be applied at each Controller or Action methods.

Share:
21,590

Related videos on Youtube

MuriloKunze
Author by

MuriloKunze

http://www.linkedin.com/pub/murilo-kunze/44/191/455

Updated on July 09, 2022

Comments

  • MuriloKunze
    MuriloKunze almost 2 years

    I would like to know how I can add Access-Control-Allow-Origin:* to my headers.

    I've tried this unsuccessfully:

    app.Use((context, next) =>
    {
        context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        return next.Invoke();
    });
    
  • Amorphis
    Amorphis over 5 years
    When app.UseMvc is last the app.UseCors... works perfectly
  • Percy
    Percy about 5 years
    Hi, using app.UseCors doesn't add a header to the response (or it doesn't seem to) but does it still achieve the same?
  • Abhinav Galodha
    Abhinav Galodha about 5 years
    @Percy - The Cors Headers are only added for the Cross-domain requests. If you are requesting from the same Origin, the ASP.net core wouldn't add the CORS headers.
  • Polynomial
    Polynomial almost 5 years
    Since it's the example here, it's worth noting that setting this particular header to * comes with security implication as it effectively disables the same-origin security policy, which can lead to cross-site request forgery attacks. Only use * when you want to open up ajax request access to the whole internet (e.g. in the context of a public API) and ensure that all non-idempotent requests you expose have some form of CSRF protection.