React调用.NET Core 7 Web API指定Origin仍遇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

