.NET 6+React CORS问题:预检成功但实际请求缺失Allow Origin
API基于.NET 6开发,前端采用最新稳定版React,相关配置如下:
后端CORS配置
... builder.Services.AddCors(); ... app.UseRouting(); app.UseCors(x => x .AllowAnyMethod() .AllowAnyHeader() .SetIsOriginAllowed(origin => true) // 允许任意源 .AllowCredentials()); // 允许携带凭证 app.UseAuthorization();
前端Axios实例配置
import axios from 'axios'; const axiosInstance = axios.create({ baseURL: 'http://domain.name/', timeout: 15000, withCredentionals: true }); export default axiosInstance;
发送POST请求时,预检OPTIONS请求响应状态为204(正常),但实际POST请求发送后,浏览器抛出“CORS missing Allow Origin”错误。已尝试在后端端点代码中手动添加响应头:
Response.Headers.Append("Access-Control-Allow-Origin", "*"); Response.Headers.Append("Access-Control-Allow-Methods", "*"); Response.Headers.Append("Access-Control-Allow-Headers", "*"); Response.Headers.Append("Access-Control-Max-Age", "86400");
修正前端拼写错误
前端Axios配置里的withCredentionals是拼写错误,正确应为withCredentials: true,这个错误会导致凭证无法正确携带,间接引发CORS校验失败。解决
AllowCredentials与通配符的冲突
当CORS配置中启用AllowCredentials()时,Access-Control-Allow-Origin不能设为*,这是浏览器的安全限制。你当前用的SetIsOriginAllowed(origin => true)本应动态返回请求的源作为Access-Control-Allow-Origin值,但实际未生效,可按以下方式调整配置:app.UseCors(x => x .AllowAnyMethod() .AllowAnyHeader() .SetIsOriginAllowed(_ => true) .AllowCredentials() .WithExposedHeaders("*")); // 若需暴露自定义响应头可添加此配置确认中间件顺序
确保UseCors中间件在UseRouting之后、UseAuthorization之前执行,避免其他中间件覆盖CORS响应头。避免手动添加冲突响应头
移除端点代码中手动添加的Access-Control-Allow-Origin: *,让CORS中间件自动处理响应头,否则会因与AllowCredentials()冲突导致浏览器报错。测试指定源配置
若动态源配置仍不生效,可先指定具体前端域名测试,排除动态匹配问题:app.UseCors(x => x .AllowAnyMethod() .AllowAnyHeader() .WithOrigins("http://your-frontend-domain.com") .AllowCredentials());
内容的提问来源于stack exchange,提问作者Reverie Metherlance

