Angular 8 - 路由在本地工作,但在生产环境中部署时,路由不起作用 - .NET Core C# 后端

问题描述

在我的应用程序中,我创建了路由,它们在本地主机上完美运行,我可以导航到:

localhost:4200/about

但是在生产环境中部署时,如果我导航到:

myapp.com/about

将会发生的是,浏览器几乎会立即将 URL 重写为:myapp.com/index.html,然后我将在浏览器导航栏中看到的最终 URL 将是认路径:“myapp .com/"

我的路由代码是:

const appRoutes: Routes = [
  { path: "",redirectTo: "/",pathMatch: "full" },{ path: "about",component: AboutComponent },{ path: "**",redirectTo: "/" },];

@NgModule({
  imports: [
      RouterModule.forRoot(appRoutes)
  ],exports: [
      RouterModule
  ]
})
export class AppRoutingModule {}

我还添加了应用模块,因为我读到它可能会有所帮助:

providers: [{provide: LocationStrategy,useClass: PathLocationStrategy}],

在后端(前端和后端在同一个项目中)这是代码

public void Configure(
....
            app.UseDefaultFiles();
            app.UseSpaStaticFiles();
            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "default",template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapSpaFallbackRoute("spa-fallback",new { controller = "Home",action = "Index" 
            });
            });
           app.UseSpa(spa => {
                spa.Options.sourcePath = "FrontEnd";
                if (env.IsDev()) {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

HomeController

  public IActionResult Index() => Redirect("index.html");

web.config 文件

<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processpath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
  </system.webServer>
</configuration>

所以基本上无论何时部署,如果我尝试导航到我的路线“/about”,它只会重写为 index.html,然后重定向到“/”

有什么想法吗?

解决方法

这对我有用,但在 IIS 服务器上。创建一个 web.config 文件并将其放在 Angular dist 文件的根文件夹中。

    <?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" />   
             </conditions>
             <action type="Rewrite" url="/frontend/" />//Folder with my Angular files
          </rule>
         </rules>
       </rewrite>
         </system.webServer>
      </configuration>