MVC中基于约定的路由的属性路由,首先调用哪个?

Attribute Routing over Convention-based Routing in MVC, which one would be called first?

我假设约定路由将首先添加到路由 table 中,因为它正在像这样 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//students

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

localhost:4200//students/40

我收到错误,我不知道为什么。当我从 RouteConfig class 中删除路由时,我能够成功调用它。

谁能给我解释一下原因和方法?

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

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

现在因为它已经匹配了一条路线,所以它不会进一步检查其他匹配项,因此您最终会出现“未找到”错误。

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

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

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 }
    );
}