Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
});
like image 494
MuriloKunze Avatar asked Apr 07 '15 23:04

MuriloKunze


2 Answers

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();
}
like image 161
Mark Amery Avatar answered Sep 25 '22 00:09

Mark Amery


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();
    }
like image 21
Blake Avatar answered Sep 27 '22 00:09

Blake