2010-12-14 38 views
6

我想弄清楚如何枚举Routes的URL在RouteTable枚举ASP.NET MVC RouteTable路由URL

在我的情况,我有以下途径定义:

routes.MapRoute 
    ("PadCreateNote", "create", new { controller = "Pad", action = "CreateNote" }); 
routes.MapRoute 
    ("PadDeleteNote", "delete", new { controller = "Pad", action = "DeleteNote" }); 
routes.MapRoute 
    ("PadUserIndex", "{username}", new { controller = "Pad", action = "Index" }); 

换句话说,如果我的网站是mysite.com,mysite.com/create调用PadController.CreateNote()和mysite.com/foobaris调用PadController.Index()

我也有一类是强类型的用户名:

public class Username 
{ 
    public readonly string value; 

    public Username(string name) 
    { 
     if (String.IsNullOrWhiteSpace(name)) 
     { 
      throw new ArgumentException 
       ("Is null or contains only whitespace.", "name"); 
     } 

     //... make sure 'name' isn't a route URL off root like 'create', 'delete' 

     this.value = name.Trim(); 
    } 

    public override string ToString() 
    { 
     return this.value; 
    } 
} 

在构造为Username,我想检查,以确保name不是定义路线。例如,如果这被称为:

var username = new Username("create"); 

然后应该抛出一个异常。我需要用什么替换//... make sure 'name' isn't a route URL off root

回答

4

这并不能完全回答你想通过阻止用户注册受保护词语来做什么,但是有一种方法可以限制你的路由。我们在我们的网站中有/用户名url,我们使用了这样的约束。

routes.MapRoute(
       "Default",            // Route name 
       "{controller}/{action}/{id}",       // URL with parameters 
       new { controller = "Home", action = "Index", id = "" }, // Parameter defaults 
       new 
       { 
        controller = new FromValuesListConstraint(true, "Account", "Home", "SignIn" 
         //...etc 
        ) 
       } 
      ); 

routes.MapRoute(
       "UserNameRouting", 
        "{id}", 
        new { controller = "Profile", action = "Index", id = "" }); 

您可能只需要保留的保留字列表,或者,如果你真的想它自动的,你可能使用反射来获取命名空间中的控制器的列表。

您可以使用它访问路线集合。这种方法的问题是它要求你显式注册你想要“保护”的所有路线。我仍然坚持我的发言,你最好有一个保留在其他地方的关键字列表。

System.Web.Routing.RouteCollection routeCollection = System.Web.Routing.RouteTable.Routes; 


var routes = from r in routeCollection 
      let t = (System.Web.Routing.Route)r 
      where t.Url.Equals(name, StringComparison.OrdinalIgnoreCase) 
      select t; 

bool isProtected = routes.Count() > 0; 
+1

向给定路线的DataTokens添加'受保护的'布尔值不是不合理的。不一定建议,但管理起来并不困难。 – 2010-12-14 19:31:36