在我的 ASP.NET Core 6 Web API 中,我按照本文启用了 CORS:MS 文章。
API 端点有效,但响应中没有预期的标头
Access-Control-Allow-Origin
:
当我尝试使用 Angular 客户端应用程序访问 API 时,出现 CORS 错误:
铬:铬
Firefox:Firefox 网络选项卡
这是我的
Program.cs
:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "EnableCORS", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed((host) => true);
});
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppConfig:Token").Value)),
ValidateIssuer = false,
ValidateAudience = false
};
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors("EnableCORS");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
我已经尝试过:
Angular 应用程序在发布到 IIS 后使用此 Web.config:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<security>
<requestFiltering>
<fileExtensions allowUnlisted="true" />
</requestFiltering>
</security>
<httpProtocol>
<customHeaders>
<remove name="X-Frame-Options" />
<remove name="Content-Security-Policy" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
将应用程序发布到 IIS 时,还需要在 web.config 中配置 CORS 策略。
示例代码:
<configuration>
<system.webServer>
<cors enabled="true" failUnlistedOrigins="true">
<add origin="*" />
<add origin="https://*.microsoft.com"
allowCredentials="true"
maxAge="120">
<allowHeaders allowAllRequestedHeaders="true">
<add header="header1" />
<add header="header2" />
</allowHeaders>
<allowMethods>
<add method="DELETE" />
</allowMethods>
<exposeHeaders>
<add header="header1" />
<add header="header2" />
</exposeHeaders>
</add>
<add origin="http://*" allowed="false" />
</cors>
</system.webServer>
有关更多信息,您可以阅读此文档。