【发布时间】:2020-09-07 21:49:39
【问题描述】:
我想通过 Asp.Net Core 3.0 API 项目启用 CORS。这是生成的基本 Asp.Net Core Api 模板。模板中的所有内容都是默认设置,除了我从文档中添加了 CORS 设置
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.AddControllers();
services.AddCors(opt =>
{
var origins = Configuration
.GetSection("AllowedHosts")
.Get<string[]>();
opt.AddPolicy("CorsPolicy", builder => builder
.WithOrigins(origins)
.AllowAnyMethod()
.AllowAnyHeader()
.Build());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
【问题讨论】:
-
对我来说似乎是对的,那代码有什么问题?
-
是的,它看起来是正确的,你能指定更多你想要实现的目标吗?
-
我从另一个应用程序调用它时遇到异常
Access to XMLHttpRequest at 'http://localhost:44314/api/Reservation' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. -
@devcrp 如果我将其更改为 services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader( ) .AllowCredentials()); });
-
我也可以从应用设置中获取值“localhost:4200”、“localhost:44349”吗?
标签: c# rest asp.net-core cors cross-domain