Below is my code:
//inside UseMvc method:
routes.MapRoute(
name: "NewRoute",
template: "/",
defaults: new { controller = "Home"});
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
we know that routing system will only find the first match route, so the first one 'NewRoute' should match the route when the application starts, because it has no action method, so I should get a 404 error page, but when I run the app, the "default" route was used, which display a normal page. so why the "NewRoute" doesn't get selected by routing system in the first place?
The fact is that NewRoute
is checked first, but routing could not find a matched action.Then it will match the next routing rule.
If you enable the Logging level to Debug
in appSettings.Development.json
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Debug"
}
}
}
and change the startup CompatibilityVersion to 2.1 (asp.net core 2.2 has another kind of EndPoint mechanism)
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
You could see the whole process in the log when you run the application:
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).
It matches twice and select the default
route.