问题描述: 在使用 ASP.NET Core w/Angular 模板时,当使用 httpget 路由时,路由被 Angular 捕获,无法匹配任何路由。
解决方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/index.html";
await next();
}
});
app.UseMvcWithDefaultRoute();
// ...
}
以上代码将在请求无法匹配到任何路由时,将请求路径重定向到 index.html
页面,以便由 Angular 处理。
app.module.ts
文件中配置正确的路由。例如:import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
// 其他路由配置
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
确保将正确的组件与对应的路由路径匹配。
app.component.html
文件中正确设置
,以便正确显示对应的组件。使用以上解决方法可以解决 ASP.NET Core w/Angular 模板中 httpget 路由被 Angular 捕获的问题。