下面是我的代码:
//inside UseMvc method:
routes.MapRoute(
name: "NewRoute",
template: "/",
defaults: new { controller = "Home"});
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
我们知道路由系统只会找到第一个匹配的路由,因此第一个'NewRoute'应该在应用程序启动时匹配该路由,因为它没有任何操作方法,因此我应该得到404错误页面,但是当我运行该应用程序,使用了“默认”路由,该路由显示一个正常页面。那么为什么路由系统不会首先选择“ NewRoute”呢?
答案 0 :(得分:1)
事实是NewRoute
首先被检查,但是路由找不到匹配的动作。然后它将匹配下一个路由规则。
如果您在Debug
中将日志记录级别启用为appSettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Debug"
}
}
}
并将启动CompatibilityVersion更改为2.1(asp.net core 2.2具有另一种EndPoint机制)
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
运行应用程序时,您可以在日志中看到整个过程:
dbug: Microsoft.AspNetCore.Routing.RouteBase[1]
Request successfully matched the route with name 'NewRoute' and template '/'
dbug: Microsoft.AspNetCore.Mvc.Internal.ActionSelector[3]
No actions matched the current request. Route values: controller=Home
dbug: Microsoft.AspNetCore.Mvc.Internal.MvcRouteHandler[3]
No actions matched the current request. Route values: controller=Home
dbug: Microsoft.AspNetCore.Routing.RouteBase[1]
Request successfully matched the route with name 'default' and template '{controller=Home}/{action=Index}/{id?}'
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
Route matched with {action = "Index", controller = "Home"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller Core22MVC.Controllers.HomeController (Core22MVC).
它匹配两次,然后选择default
路由。