I am trying to enable CORS in .NET Core in this way:
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollecti
In ASPNET CORE 2.0, The following works for me
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
});
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://localhost:5000").AllowAnyHeader()
.AllowAnyMethod());
});
services.AddMvc()
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
loggerFactory.AddConsole();
loggerFactory.AddDebug(LogLevel.Information);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Shows UseCors with named policy.
app.UseCors("AllowSpecificOrigin");
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
}
this is actually is a bug in dotnet core.
try to add cors policy right in the "Configure" method.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors(option =>
option.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
}
I just fixed my problem with Cors in Core 3.1. I was following almost every example and documentation out there. Unfortunately nothing worked until I did .Build() for the builder inside the AddPolicy portion.
services.AddCors(options => {
options.AddPolicy(
name: OrginPolicyKey,
builder => builder.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.Build() // <--- This right here
);
});
Also, other people were mentioning about calling the UseCors(OrginPolicyKey) before the rest of your routing and UseMvc stuff. That is correct and I saw that Putting UseCors after the route part broke it. Below is how mine is setup.
app.UseCors(OrginPolicyKey); // <--- First
// Then routing stuff..
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints
.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
});
Who knew a builder needs to be built ;D
You just need to add this in ConfigureService Method of StartUp Class
services.AddCors ();
and this in Configure Method of Startup Class and it will work fine then
app.UseCors (builder => builder
.AllowAnyOrigin ()
.AllowAnyHeader ()
.AllowAnyMethod ());
There is nothing more to add to enable CORS in .Net Core