MuriloKunze
MuriloKunze

Reputation: 15563

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.

I've tried this unsuccessfully:

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

Upvotes: 27

Views: 28319

Answers (4)

Mark Amery
Mark Amery

Reputation: 154545

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

Upvotes: 41

Abhinav Galodha
Abhinav Galodha

Reputation: 9878

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.

Upvotes: 2

Blake
Blake

Reputation: 308

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

Upvotes: 5

Party Ark
Party Ark

Reputation: 1159

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()).

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! The url rewrite module works perfectly well, and allows you to set outbound rules on all request.

There's a good answer here: https://stackoverflow.com/a/26545975/548664

Upvotes: 0

Related Questions