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

IIS同站点部署NextJS与ASP.NET Core时API路由失效问题

解决NextJS与ASP.NET Core同IIS站点部署时/api路由被NextJS接管的问题

问题核心是当前IIS重写规则未优先将/api请求导向ASP.NET Core应用,导致NextJS捕获了该路由。以下是具体解决步骤:

1. 调整根目录(NextJS)的web.config重写规则

在NextJS的web.config中,添加一条优先匹配/api开头请求的规则,确保这类请求直接转发到ASP.NET Core应用,不再经过NextJS的路由处理。

修改后的web.config示例:

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <!-- 优先转发/api请求到后端应用,匹配后停止后续规则处理 -->
        <rule name="Forward API Requests" stopProcessing="true">
          <match url="^api/(.*)" />
          <action type="Rewrite" url="api/{R:1}" />
        </rule>
        <!-- NextJS原有路由规则,处理非/api的请求 -->
        <rule name="NextJS Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
    <!-- 保留NextJS原有的静态文件处理等配置 -->
  </system.webServer>
</configuration>

关键说明:stopProcessing="true"确保匹配到/api的请求不会触发后续的NextJS规则,直接路由到后端应用。

2. 确认ASP.NET Core应用的web.config配置

确保后端应用的web.config启用了inheritInChildApplications="false",避免继承根目录NextJS的配置干扰后端运行:

<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\YourBackendAssembly.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

3. 验证配置与应用状态

  • 检查IIS中api应用程序的物理路径是否指向ASP.NET Core的部署目录,应用程序池的.NET Core版本与后端项目匹配。
  • 直接访问http://localhost:3005/api/your-test-endpoint,确认后端能正常响应;若失败,查看后端应用的日志排查启动或路由问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:52:49