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

ASP.NET Core+React部署至IIS后CORS跨域请求异常排查

ASP.NET Core + React 部署到IIS后CORS报错排查

错误信息

{
    "message": "Network Error",
    "name": "AxiosError",
    "stack": "AxiosError: Network Error\n    at l.onerror (http://IpAddress/static/js/main.f00ac167.js:2:700322)",
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "adapter": [
            "xhr",
            "http"
        ],
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "env": {},
        "headers": {
            "Accept": "application/json, text/plain, */*"
        },
        "method": "get",
        "url": "http://IpAddress:5030/api/user/null"
    },
    "code": "ERR_NETWORK",
    "status": null
}

Access to XMLHttpRequest at 'http://IpAddress:5030/user/noti/null' from origin 'http://IpAddress' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

部署环境

  • IIS上部署两个站点:
    • 后端站点:完整ASP.NET Core构建文件夹,端口5030
    • 前端站点:仅React构建后的wwwroot文件夹,端口80

已配置的CORS策略

Program.cs 配置

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader();
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseStaticFiles();

app.UseRouting();

app.UseCors("AllowAll");

web.config 额外配置

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

前端请求代码示例

const apiUrl = process.env.REACT_APP_API_URL;
useEffect(() => {
        const fetchData = async () => {
            try {
                const response = await axios.get(`${apiUrl}/api/admin`);
                const { data } = response.data;              
            } catch (error) {
                
            }
        };

        fetchData();
    }, []);
const handletReq = async (formData) => {
        const taskReq = {
            reply: formData.result,
        };

        axios.post(`${apiUrl}/api/admin/taskreq`, taskReq)
            .then((response) => {
                // Handle the response
            })
            .catch((error) => {
                // Handle the error
            });
    };

.env 配置

REACT_APP_API_URL=http://52.29.75.216:5000

问题

本地运行正常,但部署到IIS后出现上述CORS错误,已配置CORS策略但无效,请问可能的原因是什么?


可能的原因及解决方向

  1. 端口不匹配

    • 后端实际部署端口是5030,但.env里配置的是5000,前端请求的是错误端口,导致请求没打到正确的后端服务,自然没有CORS响应头。把REACT_APP_API_URL改成http://52.29.75.216:5030,重新构建前端再部署。
  2. 中间件顺序错误

    • ASP.NET Core中间件顺序至关重要,UseCors必须放在UseRouting之后、UseAuthorization和UseEndpoints之前。检查Program.cs是否补充了端点配置,确保顺序正确:
      app.UseRouting();
      app.UseCors("AllowAll");
      app.UseAuthorization();
      app.UseEndpoints(endpoints =>
      {
          endpoints.MapControllers();
      });
      
  3. IIS绑定或防火墙问题

    • 确认后端站点的IIS绑定是否正确,服务器防火墙是否开放5030端口。在服务器上直接访问http://52.29.75.216:5030/api/admin,如果无法返回数据,说明后端服务未正常启动或端口不通,先解决这个基础问题。
  4. IIS模块拦截预检请求

    • CORS预检请求(OPTIONS方法)可能被IIS模块拦截,导致无法到达ASP.NET Core应用。可以在web.config里补充允许OPTIONS请求的规则:
      <system.webServer>
          <handlers>
              <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
          </handlers>
          <aspNetCore processPath="dotnet" arguments=".\YourBackend.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
          <httpProtocol>
              <customHeaders>
                  <add name="Access-Control-Allow-Origin" value="*" />
                  <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
                  <add name="Access-Control-Allow-Headers" value="Content-Type, Authorization" />
              </customHeaders>
          </httpProtocol>
      </system.webServer>
      
  5. React构建环境变量未生效

    • 确认前端构建时环境变量是否正确注入。删除旧的build文件夹,重新执行npm run build,确保构建过程中读取到正确的.env变量后再部署到IIS。

内容的提问来源于stack exchange,提问作者Mohamed Yousef Khairlden

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:06:59