为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
叮当猫咪 2023-07-22 18:40:56
下面是我的代码://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”呢?
查看完整描述

1 回答

?
qq_笑_17

TA贡献1818条经验 获得超7个赞

事实是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路线。


查看完整回答
反对 回复 2023-07-22
  • 1 回答
  • 0 关注
  • 95 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信