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

.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");

解决方案
  1. 修正前端拼写错误
    前端Axios配置里的withCredentionals是拼写错误,正确应为withCredentials: true,这个错误会导致凭证无法正确携带,间接引发CORS校验失败。

  2. 解决AllowCredentials与通配符的冲突
    当CORS配置中启用AllowCredentials()时,Access-Control-Allow-Origin不能设为*,这是浏览器的安全限制。你当前用的SetIsOriginAllowed(origin => true)本应动态返回请求的源作为Access-Control-Allow-Origin值,但实际未生效,可按以下方式调整配置:

    app.UseCors(x => x
        .AllowAnyMethod()
        .AllowAnyHeader()
        .SetIsOriginAllowed(_ => true)
        .AllowCredentials()
        .WithExposedHeaders("*")); // 若需暴露自定义响应头可添加此配置
    
  3. 确认中间件顺序
    确保UseCors中间件在UseRouting之后、UseAuthorization之前执行,避免其他中间件覆盖CORS响应头。

  4. 避免手动添加冲突响应头
    移除端点代码中手动添加的Access-Control-Allow-Origin: *,让CORS中间件自动处理响应头,否则会因与AllowCredentials()冲突导致浏览器报错。

  5. 测试指定源配置
    若动态源配置仍不生效,可先指定具体前端域名测试,排除动态匹配问题:

    app.UseCors(x => x
        .AllowAnyMethod()
        .AllowAnyHeader()
        .WithOrigins("http://your-frontend-domain.com")
        .AllowCredentials());
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 07:41:20