【问题标题】:Attribute Routing over Convention-based Routing in MVC, which one would be called first?MVC 中的属性路由优于基于约定的路由,哪个会先调用?
【发布时间】:2019-03-30 01:58:38
【问题描述】:

我假设约定路由将首先添加到路由表中,因为它正在像这样在 global.asax 文件中注册

RouteConfig.RegisterRoutes(RouteTable.Routes);

现在我在 route.config 中有这样的路由

public static void RegisterRoutes(RouteCollection routes)
{            
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapMvcAttributeRoutes();
}

我有这样的属性路由

[Route("students/{id?}")]
public ActionResult Index(int? id)
{
    return View(id);
}

现在当我使用 URL 时

localhost:4200//学生

学生路线被成功调用,但是当我使用这样的路线时

localhost:4200//students/40

我收到错误,我不知道原因。当我从 RouteConfig 类中删除路由时,我可以成功调用它。

谁能解释我为什么以及如何?

【问题讨论】:

  • 我认为 MapMvcAttributeRoutes 的调用必须在 MapRoute 调用之前。
  • 你确定吗?根据 msdn 中的文档,它不是
  • 路由按照添加到路由表的顺序被调用。第一场比赛获胜,它不做任何进一步的检查。目标属性路由通常在更通用的基于约定的路由之前添加,以避免路由冲突。
  • @LijinDurairaj 除非是拼写错误,否则没有文档会显示在基于约定的路由之后添加的属性路由。
  • 感谢@Nkosi 它有效

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing


【解决方案1】:

在您的原始示例中,URL localhost:4200//students/40url: "{controller}/{action}/{id}", 基于约定的路由模板匹配。

但由于没有名为40 的操作,它将失败。

现在因为它已经匹配了一个路由,所以它不会进一步检查其他匹配,所以你最终会出现 Not Found 错误。

在 Asp.Net MVC 中,路由按照添加到路由表中的顺序被调用。第一场比赛获胜,它不会做任何进一步的检查。

目标属性路由通常在更通用的基于约定的路由之前添加,以避免像您的示例中遇到的路由冲突。

public static void RegisterRoutes(RouteCollection routes) { 
    //Attribute routes
    routes.MapMvcAttributeRoutes();

    //Convention-based routes.
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-12
    • 2015-08-11
    • 2017-03-12
    • 2013-11-02
    • 1970-01-01
    • 2017-07-16
    • 2016-09-04
    • 2018-11-17
    相关资源
    最近更新 更多