【问题标题】:How do I prevent the `Index` action appearing in my ASP.NET MVC2 urls?如何防止在我的 ASP.NET MVC2 url 中出现“索引”操作?
【发布时间】:2010-10-09 16:40:30
【问题描述】:

我有一条看起来像这样的路线(但我尝试了几种不同的路线):

routes.MapRoute(
  "Metrics",
  "Metrics/{action}/{id}/{resource}/{period}",
  new { controller = "Metrics" }
);

在MetricsController我有以下操作:

// Index sets up our UI
public ActionResult Index(int id, string resource, string period)

// GetMetrics returns json consumed by ajax graphing tool
public JsonResult GetMetrics(int id, string resource, string period)

我如何生成链接并且在 url 中没有 Index 以便我可以这样做?:

/Metrics/1234/cpu-0/10m -> MetricsController.Index(id, string resource, string period) /Metrics/GetMetrics/1234/cpu-0/10m -> MetricsController.GetMetrics(int id, string resource, string period)

我尝试了各种Html.ActionLink 和Html.RouteLink 的咒语,但没有任何乐趣。

【问题讨论】:

    标签: asp.net-mvc-2 url-routing asp.net-mvc-routing


    【解决方案1】:

    您可能需要两条路由,因为可选参数只能在路由定义的末尾:

    routes.MapRoute(
        "ActionlessMetrics",
        "Metrics/{id}/{resource}/{period}",
        new { controller = "Metrics", action = "Index" }
    );
    
    routes.MapRoute(
        "Metrics",
        "Metrics/{action}/{id}/{resource}/{period}",
        new { controller = "Metrics" }
    );
    

    并生成这些链接:

    <%= Html.ActionLink("Link1", "Index", "Metrics", 
        new { id = 123, resource = "cpu-0", period = "10" }, null) %>
    <%= Html.ActionLink("Link2", "GetMetrics", "Metrics", 
        new { id = 123, resource = "cpu-0", period = "10" }, null) %>
    

    这将导致:

    <a href="/Metrics/123/cpu-0/10">Link1</a>
    <a href="/Metrics/GetMetrics/123/cpu-0/10">Link2</a>
    

    并选择了适当的操作。

    【讨论】:

    • 谢谢达林,我认为这可能是一种方式,但想知道它是否可以只用一条路线完成。这意味着可以想象,您最终可能会在相当大的应用程序上出现路由爆炸?
    • @Kev,是的,这是可能的,特别是如果您是一些 SEO 狂人。就我个人而言,我不介意在网址中使用Index 以避免重复路线,但这是主观的。在大型应用程序中,您可能会有一些区域允许您按功能对 url 进行分组。
    【解决方案2】:

    hmmm 这个方法在 mvc2 中似乎并不适合我。无论动作方法名称仍然出现在 url 中,无论是否具有上述路由。 Html.ActionLink 仍然放入索引,例如:

    仍然在链接中产生索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多