【发布时间】:2020-05-22 06:59:12
【问题描述】:
我有 .net Core 3.0 Web API 项目,我在其中启用了给定的 CORS:
配置服务
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder => builder.AllowAnyOrigin());
});
在配置方法中
app.UseCors();
当我使用 Angular 应用程序中的 httpclient 调用此端点时,我会收到 CORS 错误。
我可以看到标题如下:
我认为在我的启动中添加 CORS 应该可以解决这个问题。
更新:
添加配置和配置服务代码:
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");
});
}
【问题讨论】:
-
你能在 Startup.cs 中显示你的 Configure() 方法代码吗?
-
@Bob 更新了问题:使用 .net Core 3.0
标签: angular asp.net-core cors