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

.NET Core API+Vue.js部署IIS后刷新/自定义URL报404求助

解决IIS部署Vue+ASP.NET Core API后刷新/直接访问子路径404的问题

一、Vue项目端配置

  • 修改vue.config.js(无则新建),设置根路径确保打包资源路径正确:
module.exports = {
  publicPath: '/',
  outputDir: 'dist' // 打包输出目录,用于后续部署
}
  • 若使用Vue Router,确认路由模式为history(hash模式无此问题,但history模式更美观),并配置根路径:
const router = createRouter({
  history: createWebHistory('/'),
  routes: [
    // 你的路由配置项
  ]
})

完成配置后打包项目,得到dist文件夹。

二、IIS端配置

1. 安装URL重写模块

IIS默认未自带该模块,需通过IIS管理器的「Web平台安装程序」搜索安装URL Rewrite。

2. 配置web.config(分两种部署场景)

场景1:Vue与API部署在同一站点(前端文件放在API项目的wwwroot目录)

在API项目的wwwroot目录(即Vue打包后dist文件所在目录)下新建/修改web.config,添加重写规则:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <!-- 非API请求转发至index.html,确保API请求正常流向后端 -->
        <rule name="SPA Route" stopProcessing="true">
          <match url="^(?!api).*$" /> <!-- 若API前缀不是api,替换为实际前缀,比如^(?!backend) -->
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

场景2:Vue与API为独立站点

在Vue打包后的dist目录下新建web.config,添加以下规则:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="SPA Route" 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="/index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

3. 验证站点基础配置

  • 确认站点物理路径指向正确目录(同站点指向API的wwwroot,独立站点指向Vue的dist)。
  • 检查站点「默认文档」列表包含index.html,无则添加。

三、ASP.NET Core后端额外配置(同站点部署场景)

在Program.cs中确保静态文件中间件顺序正确,需放在路由中间件之前:

var builder = WebApplication.CreateBuilder(args);

// 添加各类服务...

var app = builder.Build();

// 先启用静态文件服务(加载Vue前端资源)
app.UseStaticFiles();

// 再启用路由与API端点
app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.Run();

以上配置完成后,刷新或直接访问子路径时,IIS会将请求重写至index.html,由Vue Router处理前端路由,即可解决404问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 13:00:10