使用 ASP.net 核心 Angular 2 模板时,路由设置为在找不到路由时回退到 Angular 应用程序
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new {controller = "Home", action = "Index"}
);
这很好,除了它还捕获无效的 api 路由。如何添加约束,使其不会回退到以 /api 开头的路由
根据我的研究,它可以通过两种方法完成:
方法一(使用中间件(:
阅读里克·斯塔尔的博客文章
我通常不喜欢这种中间件处理,因为它会给您的路由带来更多的复杂性。
方法二(使用常规路由(:
将 apiFallback 路由放到启动.cs像这样
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers(); // here you have your api controllers with whatever routing you use (conventional or using attributes)
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
// this is your API fallback route for handling every previously unhandled route starting with api/ and send everything past api as an endpointName parameter
// remember to put this route to nearly bottom of UseEndpoints method as it's very greedy
endpoints.MapControllerRoute(
name: "apiFallback",
pattern: "api/{*endpointName}",
defaults: new { controller = "Home", action = "ApiNotFoundFallback" });
endpoints.MapFallbackToFile("index.html"); // here is your SPA page
});
现在,让我们在主控制器中创建 ApiNotFoundFallback 控制器操作(或您想要的其他任何位置 - 不要忘记相应地更改 apiFallback 路由中的默认值(
public IActionResult ApiNotFoundFallback(string endpointName)
{
return NotFound($"No endpoint matching "{endpointName}" not found!");
}
瞧!所有不由/api 启动且不由控制器处理的路由都属于索引.html所有 API "未找到"都由 ApiNotFoundFallback 操作处理。