I\'m not sure what I\'m missing, but can\'t seem to get my CORS Policy working with .NET Core 3.1 and Angular 8 client-side.
Startup.cs:
There might be several issues causing CORS error. Make sure to configure CORS properly first. You can configure it in the below way:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
Then in Configure() of Startup.cs file, the following should be the order of middlewares:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("../swagger/v1/swagger.json", "API");
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
If you have configured the .NET core application to run on HTTPs URL, then make sure to invoke the https URL of the application for API request from Angular as well.
If you are invoking HTTP URL from the Angular and running .NET core application on HTTPs, then remove the app.UseHttpsRedirection() middleware.
To use app.UseHttpsRedirection(), either run .NET core on HTTPs URL and make HTTPs requests from the angular or run .NET core on HTTP URL and make HTTP requests from the angular (in this case, the .NET application must only run on HTTP. It shouldn't be configured to run on both HTTP and HTTPs).
The above things will most probably solve your problem.