繁体   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