我创建了一个后端Net Core API,可在VS和Postman中使用。 但是,在创建Angular CLI前端时,出现此错误。这没有任何意义,因为我在下面启用了为AllowAnyOrigin添加Cors。
角度错误:
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://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2
答案 0 :(得分:2)
您还需要将CORS中间件添加到管道中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("AllowAllOrigins");
// Other middleware
}
调用AddCors()时,您将添加CORS中间件所需的服务,并定义策略。 但是您也需要在中间件管道中应用该策略。