问题
I have .net Core 3.0 Web API project where I have enabled the CORS as given:
ConfigureService
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder => builder.AllowAnyOrigin());
});
And in Configure method
app.UseCors();
And when ever I call this end point using httpclient from angular application I get CORS error.
And I can see the headers as in :
I thought adding the CORS in my startup should have solved this issue.
UPDATE:
Adding Configure and Configure Service Code:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<LabSoftwareContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LabDatabase")));
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Lab API",
Description = "Lab Software APIs"
});
});
services.Configure<IISServerOptions>(options =>
{
options.AutomaticAuthentication = false;
});
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("AllowOrigin");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Lab Software API");
});
}
回答1:
I think the root cause of this is the order of your middleware in Configure()
- if the order is incorrect it can cause unexpected Cors failures.
e.g. I think UseCors()
might need to be placed after UseHttpsRedirection()
There is a (complex!) table explaining the ordering of middleware here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1#built-in-middleware
Your code modified according to the example from the same page:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Lab Software API");
});
}
回答2:
[EnableCors("your_policy")]
public class BaseController : apiController
One thing that worked for me was to that despite putting on the Configure method was that i needed to specify the CORS in the controllers.
回答3:
write these at the end of Configure method
app.UseCors(x=>x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); app.UseAuthentication();app.UseMvc();
also change https to http
来源:https://stackoverflow.com/questions/60091440/cors-error-keep-happening-even-after-enabling-it-with-net-core-and-angular-cli