我正在使用纯 javascript 请求 .NET 6 中的 Minimal API,但是当我在浏览器中打开它时,我收到以下消息:
CORS 策略已阻止从源“null”获取“https://localhost:7252/v1/todos”的访问权限:请求的资源上不存在“Access-Control-Allow-Origin” header 。不透明的响应满足您的需求,将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
我已经在 API 中添加了 CORS 配置,但它不起作用:
fetch('https://localhost:7252/v1/todos')
.then(response => response.json()) ...
builder.Services.AddCors(options => options.AddDefaultPolicy(builder =>
{
builder.WithOrigins(
"https://localhost:7252/v1/todos",
"https://localhost:7252");
}));
app.UseCors();
最佳答案
你可能想稍微扩展一下
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
这里有一个完整的代码示例public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
// services.AddResponseCaching();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
// app.UseResponseCaching();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Asp Cors Sample
关于javascript - Javascript 和 .NET Minimal API 中的 CORS 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69802631/