簡體   English   中英

Angular 8 - 路由在本地工作,但在生產環境中部署時,路由不起作用 - .NET 核心 C# 后端

[英]Angular 8 - routing works locally, but when deployed on Production, routes don't work - .NET Core C# backend

在我的應用程序中,我創建了路線,它們在 localhost 上完美運行,我可以導航到:

localhost:4200/about

但是當部署在生產上時,如果我導航到:

myapp.com/about

將會發生的事情是,瀏覽器幾乎會立即將 URL 重寫為: myapp.com/index.html ,然后緊接着最終的 url 將在瀏覽器的導航欄中顯示: 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM