Search code examples
angularasp.net-coreroutessingle-page-applicationfallback

How to manage HTML5 route fallback with parameter for Angular SPA with ASP.NET Core in Startup.cs?


I was searching, but did not manage finding any answer, maybe here someone smart knows what to do. I have Angular SPA, with ASP.NET Core back-end. In Angular I dont want to use Hash Bang Routes. But I have no idea how to configure routing, to be able to refresh or enter a SPA component page with a parameter. For example: somewebsite.com/a5eccbd9 //where a5eccbd9 is a parameter.

Examples closest to my problem, but routing just to index.html of the SPA.

https://stackoverflow.com/a/61275033

https://weblog.west-wind.com/posts/2017/aug/07/handling-html5-client-route-fallbacks-in-aspnet-core#Letting-ASP.NET-Core-Handle-Client-Side-Routes

https://weblog.west-wind.com/posts/2020/Jul/12/Handling-SPA-Fallback-Paths-in-a-Generic-ASPNET-Core-Server#handling-fallbacks-with-built-in-endpoints-and-route-processing

But after being routed to the file, what next to do with parameter and being redirected to the correct component? My Angular routing:

const routes: Routes = [
...
  {
    path: '',
    component: FormComponent,
  },
  {
    path: ':id',
    component: FormComponent,
  },
...
];

And in index.html I have: <base href="/" />

And in my dead end I have no idea how to make back-end redirecting me properly.


Solution

  • Actually fallback routing for the Angular was easier than I expected. In the back-end I just needed to add end-point mapping:

    app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                    endpoints.MapFallbackToFile("/{id}", "/index.html"); //<- added
                    endpoints.MapFallbackToFile("/", "/index.html");
                });
    

    And from now on after GET request: somewebsite.com/a5eccbd9 ASP.NET Core redirects it to the Angular SPA's index.html, and over there Angular's routing deal with that oryginal request by its own routing path: ':id',.

    I was also considering solution from here: Angular2: How to access index.html querystring in App Component where from ASP.NET Core I wanted to redirect it to: index.html?id={id}, and in main app component to catch id, but Angular appeared to be smarter than I expected.