Reputation:
I created a backend Net Core API which works in VS and Postman. However, when creating an Angular CLI front end, I receive this error. It does not make sense, since I enabled Add Cors for AllowAnyOrigin Below.
Angular error:
Access to XMLHttpRequest at 'https://localhost:xxxx/api/values' from origin 'http://localhost:xxxx' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Startup.cs
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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors((options =>
{ options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin());}));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors();
// Shows UseCors with CorsPolicyBuilder.
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2
Upvotes: 1
Views: 1478
Reputation: 58873
You need to add the CORS middleware to the pipeline as well:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("AllowAllOrigins");
// Other middleware
}
When you call AddCors(), you are adding the services needed by the CORS middleware, as well as defining a policy. But you need to apply the policy in the middleware pipeline as well.
Upvotes: 1