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

React调用.NET Core 7 Web API指定Origin仍遇CORS错误求助

.NET Core 7 Web API CORS指定源不生效问题排查

我搭建了一个.NET Core 7 Web API,尝试从React应用调用,但配置指定源的CORS策略时始终报错,允许所有源则正常工作,需要排查原因。

后端指定源的CORS配置

builder.Services.AddCors(p => p.AddPolicy("corspolicy", builder =>
{
    builder
    .WithOrigins("http://localhost:3000/")
    //.AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader();
}));

app.UseCors("corspolicy");

前端调用时的报错信息

Access to fetch at 'https://localhost:7063/api/CloneAPI' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Access to fetch at 'https://localhost:7063/api/CloneAPI' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

后端允许所有源的生效配置

builder.Services.AddCors(p => p.AddPolicy("corspolicy", builder =>
{
    builder
    //.WithOrigins("http://localhost:3000/")
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader();
}));

app.UseCors("corspolicy");

前端调用代码

const [posts, setPosts] = useState([]);

useEffect(() => {
  fetch("https://localhost:7063/api/CloneAPI")
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
      setPosts(data);
    })
    .catch((err) => {
      console.log(err.message);
    });
}, []);

解决方案

1. 移除Origin末尾的斜杠

浏览器发送的请求Origin是http://localhost:3000(无末尾斜杠),而配置中写的是http://localhost:3000/,两者不匹配导致CORS策略不生效。修改配置:

builder.Services.AddCors(p => p.AddPolicy("corspolicy", builder =>
{
    builder
    .WithOrigins("http://localhost:3000") // 去掉末尾斜杠
    .AllowAnyMethod()
    .AllowAnyHeader();
}));

2. 确认中间件顺序

app.UseCors必须放在app.UseRouting之后、app.UseAuthorization之前,否则无法正确添加CORS响应头。正确的中间件顺序示例:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddCors(p => p.AddPolicy("corspolicy", builder =>
{
    builder.WithOrigins("http://localhost:3000")
           .AllowAnyMethod()
           .AllowAnyHeader();
}));

var app = builder.Build();

app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("corspolicy"); // 关键位置
app.UseAuthorization();

app.MapControllers();

app.Run();

3. 验证Origin的准确性

确保配置的Origin和前端实际运行的地址完全一致,包括协议(HTTP/HTTPS)、域名、端口,不要出现拼写错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 07:57:20