且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC - 捕获所有路由和默认路由

更新时间:2023-02-16 18:41:26

使用路由约束

在您的情况下,您应该定义默认路由 {controller}/{action}/{id} 并对其施加约束.可能与控制器名称甚至动作有关.然后把catch全部放在它后面,它应该可以正常工作.

Use route constraints

In your case you should define your default route {controller}/{action}/{id} and put a constraint on it. Probably related to controller names or maybe even actions. Then put the catch all one after it and it should work just fine.

因此,当有人请求未通过约束的资源时,catch-all 路由将匹配请求.

So when someone would request a resource that fails a constraint the catch-all route would match the request.

所以.首先使用路由约束定义默认路由,然后在它之后捕获所有路由:

So. Define your default route with route constraints first and then the catch all route after it:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new { controller = "Home|Settings|General|..." } // this is basically a regular expression
);
routes.MapRoute(
    "NotFound",
    "{*url}",
    new { controller = "Error", action = "PageNotFound" }
);