Azure托管ASP.NET Core 8 Web API本地React访问CORS失败求助
问题描述
部署在Azure上的ASP.NET Core 8.0 Web API运行正常,但本地用React前端(http://localhost:3000)调用API时触发CORS拦截,报错:
Access to fetch at 'https:///api/stats' 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.
已按文档配置CORS策略,包括添加服务、调整中间件顺序,甚至尝试在控制器加[EnableCors]特性、开放所有源,但均无效。
排查与解决方案
1. 修正API请求地址
报错里的请求地址https:///api/stats缺少主机/端口部分,本地调试时应指向https://localhost:<端口>/api/stats或http://localhost:<端口>/api/stats。先确认前端请求的API地址是否正确指向本地调试的API服务,地址错误会导致CORS策略无法匹配。
2. 验证CORS策略常量定义
检查MyAllowSpecificOrigins常量的拼写和定义,确保它是有效的字符串(比如public const string MyAllowSpecificOrigins = "MyAllowSpecificOrigins";),常量名称错误会导致策略无法加载。
3. 规范中间件顺序(核心)
确保UseCors的位置在UseRouting之后、UseAuthentication和UseAuthorization之前,不要同时在全局中间件和控制器端点重复指定策略,二选一即可:
// 方式一:全局应用CORS策略 app.UseRouting(); app.UseCors(MyAllowSpecificOrigins); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); // 方式二:仅在控制器端点启用CORS app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers() .RequireCors(MyAllowSpecificOrigins); });
4. 检查本地HTTPS配置
如果本地API启用HTTPS,而前端是HTTP(http://localhost:3000),要么在CORS策略中明确允许HTTP源,要么将前端切换到HTTPS调试。也可以临时禁用API的HTTPS(修改launchSettings.json的applicationUrl为HTTP地址)来验证问题。
5. 排查Preflight请求拦截
检查是否有自定义中间件在CORS之前处理了OPTIONS请求,导致CORS响应头未被添加。可以添加调试日志,跟踪OPTIONS请求的处理流程,确认CORS中间件是否被正确执行。
6. 临时通配符验证(排查源配置问题)
临时将CORS策略改为允许所有源,验证是否能正常访问:
options.AddPolicy(MyAllowSpecificOrigins, policy => { policy.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); });
如果此配置有效,说明之前的WithOrigins存在源地址拼写错误、带尾斜杠不匹配等问题。注意:生产环境禁止同时使用AllowAnyOrigin和AllowCredentials,浏览器会拦截此类配置。
内容的提问来源于stack exchange,提问作者Joe B

