[英]C# Net Core: After enabling Cors in API, it still states blocked by CORS policy
我創建了一個可以在VS和Postman中使用的后端Net Core API。 但是,在創建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.
啟動文件
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/zh-cn/aspnet/core/security/cors?view=aspnetcore-2.2
您還需要將CORS中間件添加到管道中:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("AllowAllOrigins");
// Other middleware
}
調用AddCors()時,您將添加CORS中間件所需的服務,並定義策略。 但是您也需要在中間件管道中應用該策略。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.