如何在 Startup.cs 中使用 ASP.NET Core 的 Angular SPA 参数管理 HTML5 路由回退?

问题描述

我正在搜索,但没有找到任何答案,也许这里有聪明的人知道该怎么做。我有 Angular SPA,带有 ASP.NET Core 后端。在 Angular 中,我不想使用 Hash Bang Routes。但是我不知道如何配置路由,以便能够使用参数刷新或进入 SPA 组件页面。例如:somewebsite.com/a5eccbd9 //where a5eccbd9 is a parameter

最接近我的问题的示例,但仅路由到 SPA 的 index.html

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

但是在路由到文件之后,接下来如何处理参数并重定向到正确的组件?我的 Angular 路由:

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

index.html 我有<base href="/" />

在我的死胡同里,我不知道如何让后端正确重定向我。

解决方法

试试这个:

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

在你的component.ts中,你可以通过调用在ngOnInit方法上使用这个来获取id:

import { ActivatedRoute } from '@angular/router';

constructor(
    private route: ActivatedRoute
  ) { }
  
ngOnInit() {
  const id = this.route.snapshot.params.id);
}

,

实际上,Angular 的回退路由比我预期的要容易。在后端,我只需要添加端点映射:

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

从现在开始,在 GET 请求之后:somewebsite.com/a5eccbd9 ASP.NET Core 将它重定向到 Angular SPA 的 index.html,在那里 Angular 的路由通过它自己的路由 {{1} }.

我也在考虑这里的解决方案:Angular2: How to access index.html querystring in App Component 我想从 ASP.NET Core 重定向到:path: ':id',,并在主应用程序组件中捕获 index.html?id={id},但是 Angular似乎比我预期的更聪明。