You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 7.0配置CORS遇跨域问题求助

前后端分离应用CORS配置问题

问题背景

部署前后端分离应用:前端基于React,后端ASP.NET Core 7.0部署在Windows IIS服务器。前端请求头设置如下:

const headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append("Content-Type", "application/json");

按照微软文档配置CORS后,前端请求报错:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

后端Program.cs代码:

var builder = WebApplication.CreateBuilder(args);

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                policy =>
                  {
                      string[] origins = { "https://myfrontendurl.fr" };

                      policy.WithOrigins(origins)
                            .AllowAnyHeader()
                            .AllowAnyMethod();
                  });
});

// Add services to the container.
builder.Services.AddControllers().AddNewtonsoftJson();

var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();
app.MapControllers();

app.Run();

尝试在IIS添加自定义响应头后,出现新错误:

Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'https://myfrontendurl.fr, https://myfrontendurl.fr', but only one is allowed

需求:不使用IIS CORS模块,由应用自身管理CORS,排查问题原因并解决。


解决步骤

1. 清理IIS中的CORS相关配置

彻底删除IIS站点/服务器级别添加的Access-Control-Allow-Origin自定义响应头,避免和ASP.NET Core的CORS配置重复输出。如果之前安装过IIS CORS模块,直接卸载或在站点web.config中禁用:

<system.webServer>
  <modules>
    <remove name="CorsModule" />
  </modules>
</system.webServer>

2. 修正前端请求头错误

前端代码中不要设置Access-Control-Allow-Headers请求头,这个是后端返回的响应头字段,不是前端发送的请求头。正确的请求头只需保留Content-Type:

const headers = new Headers();
headers.append("Content-Type", "application/json");

3. 确认中间件顺序正确性

当前Program.cs中UseCors的位置是正确的,但需再次确认:

  • UseCors必须放在UseAuthorization和MapControllers之前
  • 如果站点同时托管静态资源,UseCors要放在UseStaticFiles之后

4. 明确指定控制器的CORS策略

在控制器或Action上添加[EnableCors]特性,确保策略被精准应用:

[ApiController]
[Route("api/[controller]")]
[EnableCors("_myAllowSpecificOrigins")]
public class DemoController : ControllerBase
{
    // 接口逻辑
}

5. 验证预检请求响应

用curl或Postman发送OPTIONS预检请求,检查响应头是否包含正确的Access-Control-Allow-Origin:

curl -X OPTIONS https://你的后端API地址/api/示例接口 \
-H "Origin: https://myfrontendurl.fr" \
-H "Access-Control-Request-Method: POST"

如果响应头中存在目标Origin,说明后端配置生效,问题可能出在前端缓存或浏览器跨域策略限制。


内容的提问来源于stack exchange,提问作者supergalou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 18:13:28