首页 > 解决方案 > 在 Angular 10 ASP.NET Core 3.1 SPA 应用程序中处理浏览器重新加载的正确方法是什么?

问题描述

我一直在使用Microsoft的Content Reactor 示例应用程序。我已经升级了 Angular、.NET Standard、.NET Core 和各种 NuGet 包的版本。该应用程序现在使用带有端点路由的 Angular 10 和 ASP.NET Core 3.1。

我知道这SpaServices/UseSpa()已被弃用。

        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501
        });

该站点正在开发/Visual Studio 中的本地主机上工作。但是,浏览器重新加载会导致 404 错误(例如,对于https://localhost:2297/home)。我知道这可能是由于应用程序的 SPA 特性。

鉴于 SpaServices 的弃用,支持浏览器按钮重新加载的正确方法是什么?

更新:该应用程序正在部署到 Microsoft Azure 应用程序服务。该应用程序使用 SignalR。

标签: angularsingle-page-applicationasp.net-core-3.1

解决方案


为您的 IIS 服务器创建一个 web.config 文件,将 404 重定向到 index.html 以便 Angular 可以处理它们,例如:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <httpErrors>
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" prefixLanguageFilePath="" path="/" responseMode="ExecuteURL" />
    </httpErrors>
    <caching enabled="false" enableKernelCache="false" />
    <rewrite>
      <rules>
        <rule name="HTTPS Redirect" stopProcessing="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="^OFF$" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

推荐阅读