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();
});
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();
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With