第一个匹配路由必须同时指定控制器和操作?

下面是我的代码:


//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”呢?


叮当猫咪
浏览 99回答 1
1回答

qq_笑_17

事实是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=Homedbug: Microsoft.AspNetCore.Mvc.Internal.MvcRouteHandler[3]      No actions matched the current request. Route values: controller=Homedbug: 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路线。
打开App,查看更多内容
随时随地看视频慕课网APP