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

解决IIS中Angular 8无哈希路由SPA刷新404错误问题

解决IIS中Angular与ASP.NET Core Web API共存时刷新404问题

1. 修正web.config重写规则

现有规则的转发目标指向/,需改为直接指向Angular入口文件index.html,同时新增规则排除API路由,避免API请求被错误转发:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Angular Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <!-- 排除API路由,保证Web API正常响应 -->
            <add input="{REQUEST_URI}" pattern="^/api/" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>
      </rules>
    </rewrite>
    <httpErrors>
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" prefixLanguageFilePath="" path="/index.html" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>
</configuration>

2. 配置ASP.NET Core fallback路由

在后端代码中添加fallback规则,让ASP.NET Core优先处理API请求,其余请求转发给Angular:

.NET 6+(Program.cs)

app.MapControllers(); // 先映射API控制器
app.MapFallbackToFile("/index.html"); // 非API请求转发到Angular入口
app.Run();

旧版本(Startup.cs)

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...其他中间件配置
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers(); // 处理API请求
        endpoints.MapFallbackToFile("/index.html"); // 兜底转发到Angular
    });
}

3. 验证基础配置

  • 确认Angular的<base href="/">配置正确,构建时需保证使用--base-href /参数(或在angular.json中设置baseHref: "/")
  • 检查IIS是否启用URL Rewrite模块,未安装则重写规则无法生效

4. 重新部署生效

  • 清空IIS站点根目录旧文件,重新发布Angular项目到wwwroot
  • 重启IIS站点,确保所有配置生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:07:52