简体   繁体   English

为什么 ASP.NET MVC 路由有名称?

[英]Why does an ASP.NET MVC route have a name?

In an ASP.NET MVC 5 web application, there is a RouteConfig class that registers many routes.在 ASP.NET MVC 5 Web 应用程序中,有一个注册许多路由的 RouteConfig 类。 In all of the examples I have seen so far, only the "Default" route has a non-empty name.到目前为止,在我看到的所有示例中,只有“默认”路由具有非空名称。 The URL pattern and default route values seem to be sufficient to correctly associate any URL to the controller and action to execute. URL 模式和默认路由值似乎足以将任何 URL 正确关联到控制器和要执行的操作。 So, is there any benefit to naming a route?那么,命名路由有什么好处吗? For debugging or logging?用于调试或日志记录? Just for self-documenting the code?只是为了自我记录代码?

For example:例如:

public class RouteConfig
{
  public static void RegisterRoutes( RouteCollection routes )
  {
    routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" );

    // Most pages.
    routes.MapRoute( name: "Default",
      url: "{controller}/{action}/{id}",
      defaults: new { controller = "home", action = "index", id = UrlParameter.Optional }

    // A special page.
    // Should the route have a name?
    routes.MapRoute( name: "",
      url: "special",
      defaults: new { controller = "special", action = "index", HttpVerbs = HttpVerbs.Get } );
  }
}

The main reason to name a route is so that if you need a link to a route from somewhere in the app, you can reference the name.命名路线的主要原因是,如果您需要从应用程序中的某处链接到路线,您可以引用该名称。 That way if the actual URL/path changes you don't break everywhere in the code that references that route.这样,如果实际的 URL/路径发生变化,您就不会在引用该路由的代码中处处中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM