How to enable CORS in ASP.net Core WebAPI
Because you have a very simple CORS policy (Allow all requests from XXX domain), you don't need to make it so complicated. Try doing the following first (A very basic implementation of CORS).
If you haven't already, install the CORS nuget package.
Install-Package Microsoft.AspNetCore.Cors
In the ConfigureServices method of your startup.cs, add the CORS services.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(); // Make sure you call this previous to AddMvc
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Then in your Configure method of your startup.cs, add the following :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Make sure you call this before calling app.UseMvc()
app.UseCors(
options => options.WithOrigins("http://example.com").AllowAnyMethod()
);
app.UseMvc();
}
Now give it a go. Policies are for when you want different policies for different actions (e.g. different hosts or different headers). For your simple example you really don't need it. Start with this simple example and tweak as you need to from there.
Further reading : http://dotnetcoretutorials.com/2017/01/03/enabling-cors-asp-net-core/
How to enable cors in ASP.NET Core 6.0 Web API project?
The code that you posted seems to work fine. I pasted the code into a new .NET 6 project and the CORS headers are added in the response when a request like below is send from the browser.
fetch('http://localhost:7107/Weatherforecast').then(res => res.json()).then(e => console.log(e))
Results in the following response:
How to enable CORS in Asp.Net Core 3.0 WebAPI
The order of precedence for Cors
should be before adding controllers. It should be added as define in the official documentation: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
Follow this code:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200", "http://localhost:44349")
.AllowAnyMethod()
.AllowAnyHeader();
//.AllowCredentials());
});
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
As per the official documentation, it must be noted that:
Specifying AllowAnyOrigin and AllowCredentials is an insecure
configuration and can result in cross-site request forgery. The CORS
service returns an invalid CORS response when an app is configured
with both methods.
How to enable CORS in ASP.NET Core
For ASP.NET Core 6:
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
// services.AddResponseCaching();
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.MapControllers();
app.Run();
See the official docs for more samples.
For ASP.NET Core 3.1 and 5.0:
You have to configure a CORS policy at application startup in the ConfigureServices
method:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins("http://example.com")
.AllowAnyMethod()
.AllowAnyHeader();
}));
// ...
}
The CorsPolicyBuilder
in builder
allows you to configure the policy to your needs. You can now use this name to apply the policy to controllers and actions:
[EnableCors("MyPolicy")]
Or apply it to every request:
public void Configure(IApplicationBuilder app)
{
app.UseCors("MyPolicy");
// ...
// This should always be called last to ensure that
// middleware is registered in the correct order.
app.UseMvc();
}
I'm getting CORS error with CORS configured on ASP.NET Core Web API app
So it looks like the Framework on Backend side just have some problems (I don't know how to describe it). When I restarted my PC and then rebuild my App, everything works fine.
Thanks everyone for every comment /p>
Related Topics
How to Wait For a Thread to Finish With .Net
When Should I Use Double Instead of Decimal
Why Is There No Foreach Extension Method on Ienumerable
Call a Stored Procedure With Parameter in C#
C# Error: "An Object Reference Is Required For the Non-Static Field, Method, or Property"
How to Retrieve Id of Inserted Entity Using Entity Framework
Why Response.Redirect Causes System.Threading.Threadabortexception
How to Create and Use Resources in .Net
What Is the Purpose of the "Prefer 32-Bit" Setting in Visual Studio and How Does It Actually Work
Catch Multiple Exceptions At Once
Could Not Establish Trust Relationship For Ssl/Tls Secure Channel - Soap
Converting String to Byte Array in C#
C# Getting the Path of %Appdata%
Best Timer For Using in a Windows Service
What's the Difference Between an Object Initializer and a Constructor