.NET 6与React集成时CORS策略错误的解决方法求助
问题复现
前端React(http://localhost:3000)调用.NET 6后端API(http://localhost:5087/api/GetPlayerById/2)时触发CORS错误:
Access to XMLHttpRequest at 'http://localhost:5087/api/GetPlayerById/2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
API在Postman、直接浏览器访问均正常,仅React调用失败。
排查与修复步骤
1. 完善CORS策略配置
当前配置仅指定了允许的源,但默认未开放HTTP方法和请求头,React发起的请求可能包含自定义头或使用POST/PUT等方法,导致CORS校验失败。修改Program.cs中的CORS策略:
builder.Services.AddCors(options => { options.AddPolicy(name: MyAllowSpecificOrigins, policy => { policy.WithOrigins("http://localhost:3000") .AllowAnyMethod() // 允许所有HTTP方法 .AllowAnyHeader(); // 允许所有请求头 }); });
2. 确认中间件顺序
确保UseCors的位置正确,必须在UseRouting之后、UseAuthorization之前,你的代码当前顺序合规,若后续新增中间件需保持此顺序:
app.UseRouting(); app.UseCors(MyAllowSpecificOrigins); // 位置正确 app.UseAuthorization();
3. 临时禁用HTTPS重定向
后端运行在HTTP协议(http://localhost:5087),但代码中启用了app.UseHttpsRedirection();,会将HTTP请求重定向到HTTPS,可能导致CORS校验失效。暂时注释该中间件测试:
// app.UseHttpsRedirection();
4. 移除SPA代理环境变量
launchSettings.json中配置的ASPNETCORE_HOSTINGSTARTUPASSEMBLIES=Microsoft.AspNetCore.SpaProxy可能与CORS策略冲突,移除该环境变量:
修改两个profile的environmentVariables:
"environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" // 移除ASPNETCORE_HOSTINGSTARTUPASSEMBLIES配置 }
5. 显式在控制器启用CORS
若全局策略未生效,可在目标控制器或Action上添加[EnableCors]特性强制应用策略:
using Microsoft.AspNetCore.Cors; [ApiController] [Route("api/[controller]")] [EnableCors("_myAllowSpecificOrigins")] // 指定策略名称 public class PlayerController : ControllerBase { // 你的API方法 }
验证修复
修改后重启后端服务,重新发起React请求,可在浏览器开发者工具Network标签中查看响应头,确认是否包含Access-Control-Allow-Origin: http://localhost:3000。
内容的提问来源于stack exchange,提问作者HeyLameRobin

