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

IIS Express调试时带凭证的CORS预检请求问题排查咨询

CORS配置下POST请求预校验失败问题排查与修复

配置信息

后端Program.cs配置

builder.Services.AddCors();

var app = builder.Build();
 
app.UseRouting();

app.UseCors(x => x.AllowAnyMethod().AllowAnyHeader().AllowCredentials().SetIsOriginAllowed(origin => true));
 
app.UseAuthentication();

前端Axios客户端配置

const axiosClient = axios.create({
   baseURL: configuration.apiUrl,
   headers: { "Content-type": "application/json" },
   withCredentials: true });

服务器LaunchSettings.json配置

"CustomProfile": {
      "commandName": "IISExpress",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    },
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:60737",
      "sslPort": 44358
    }
  }

问题现象

  • GET请求axiosClient.get('records').then((res: AxiosResponse) => res.data)正常返回200,后端认证流程完成
  • POST请求axiosClient.post('record', createCommand).then((res: AxiosResponse) => res.data)触发CORS错误:

Access to XMLHttpRequest at 'https://localhost:44358/api/records' from origin 'https://localhost:44414' 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.

可能原因

  1. Windows身份验证拦截预校验请求:当前IIS配置开启了Windows身份验证、禁用匿名验证,而POST请求带JSON内容会触发OPTIONS预校验请求,这类请求默认是匿名发送的,会被IIS直接拦截,导致ASP.NET Core的CORS中间件无法处理并返回所需响应头。
  2. 中间件执行逻辑隐患:虽已将UseCors放在UseAuthentication之前,但预校验请求未通过IIS的身份验证关卡,根本没到达CORS中间件。

修复方案

方案1:允许OPTIONS请求匿名访问

在项目根目录创建或修改web.config,添加以下配置,让IIS对OPTIONS请求跳过身份验证:

<configuration>
  <system.webServer>
    <security>
      <authorization>
        <add accessType="Allow" users="*" verbs="OPTIONS"/>
      </authorization>
    </security>
  </system.webServer>
</configuration>

这样预校验请求就能顺利到达ASP.NET Core的CORS中间件,返回正确的响应头。

方案2:优化CORS配置与中间件顺序

将CORS策略显式命名,并确保中间件顺序严格遵循UseCors→UseAuthentication→UseAuthorization的顺序:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyMethod()
              .AllowAnyHeader()
              .AllowCredentials()
              .SetIsOriginAllowed(origin => true);
    });
});

var app = builder.Build();

app.UseRouting();

// 优先启用CORS策略
app.UseCors("AllowAll");

// 再执行认证、授权逻辑
app.UseAuthentication();
app.UseAuthorization();

// 映射控制器路由
app.MapControllers();

方案3:校验路由匹配规则

确认后端/api/record的POST路由配置正确,避免因路由不匹配导致请求未进入CORS中间件的处理流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 10:55:22