0

在 asp.net mvc 中使用默认路由并使用 ActionLink 的结果

@Html.ActionLink("title", "Index", "Question", new { id = 25}, null)

是 :

http://localhost/question/index/25

将链接更改为

http://localhost/question/25

我在默认之前在 Global.asax 中添加了新的路由角色:

routes.MapRoute(
            "default2", // Route name 
            "Question/{id}", // URL with parameters
            new { controller = "Questions", action = "Index", id = UrlParameter.Optional} // Parameter defaults
        );

我对用户、标签、....有同样的问题,我应该为每个主题创建相同的角色吗?

4

2 回答 2

2

你试过这个吗?

  routes.MapRoute(
      "", 
      "{controller}/{id}",
      new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
  );

更新:

如果id始终是整数,那么您可以在上述路由中放置一个简单的数字约束,以避免@Nick 报告的路由问题。

  routes.MapRoute(
      "my-route",
      "{controller}/{id}",
      new { controller = "Home", action = "Index", id = UrlParameter.Optional },
      new { id = @"\d*" }
  );
于 2012-05-21T13:27:40.710 回答
1

我想我会更进一步,向您展示如何创建路由约束,这样您就不需要注册三个单独的路由。

使用以下文章作为指南,您可以创建一个约束,该约束将根据您将指定的控制器列表验证当前路由控制器:

http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-custom-route-constraint-cs

所以这是我的带有路由约束的课程:

public class ControllerConstraint : IRouteConstraint
{
    private string[] _controllers;

    public ControllerConstraint() : this(null) { }
    public ControllerConstraint(string[] controllers)
    {
        _controllers = controllers;
    }

    #region IRouteConstraint Members
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        string  currentController = values.ContainsKey("controller")?  values["controller"].ToString() : null;

        return _controllers != null //The list of controllers passed to the route constraint has at least one value in it
            && !String.IsNullOrEmpty(currentController) //The current route data has a controller in it to compare against
            && (from c in _controllers where c.Equals(currentController,StringComparison.CurrentCultureIgnoreCase) select c).ToList().Count > 0; //We find a match of the route controller against the list of controllers
    }
    #endregion
}

从那里您需要做的就是修改在 Globa.asax 中注册路线的方式

 routes.MapRoute(
      "Action-less Route", // Route name
      "{controller}/{id}", // URL with parameters
      new { controller = "Questions", action = "Index", id = UrlParameter.Optional}, //Parameter defaults
      new {isController = new ControllerConstraint(new string[] {"Questions","Users","Tags"})} //Route Constraint
        ); 

您还可以更进一步,验证 {id} 是一个带有附加路由约束的数字,如下所示:

http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-route-constraint-cs

于 2012-05-21T13:59:49.717 回答