Vue Router 搭配 ASP.NET Core 3.1 時 設定history mode

  • 778
  • 0

Vue Router 搭配 ASP.NET Core 3.1 時 設定history mode

相信也有其他人的Vue搭配後端時是把產生出倆的 index.html 貼到其它檔案裡面
例如貼到 PHP, Aspx
我的例子是貼到ASP.NET Core 的cshtml

Vue Router 搭配IIS的官方範例是調整web.config的設定

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Handle History Mode and custom 404/500" 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>
  </system.webServer>
</configuration>

使用 Url Rewrite 在找不到檔案、資料夾的時候都回應根目錄的內容
但搭配 ASP.Net Core 時這樣設定會使得讀取 js,css 檔時 IIS 也都回應 index.html
這是因為我們真正的 js,css 檔是藏在 /wwwroot/js, /wwwroot/css 裡面
IIS自己去找會找不到,正常使用時是Kestrel去把檔案帶出來的

其實不用動web.config,只需要在Startup.csConfigure裡面加一行就可以了

endpoints.MapFallbackToController("Index","Home");


這樣也會在找不到檔案時fallback回我們指定的Controller

參考資料 Trouble with URL rewrite using Vue Router HTML5 History Mode on Azure Web App