枚举ASP.NET MVC RouteTable路由URL

时间:2010-12-14 18:28:10

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

我正在尝试弄清楚如何在Routes中枚举RouteTable的网址。

在我的场景中,我定义了以下路线:

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需要什么?

1 个答案:

答案 0 :(得分:5)

通过阻止用户注册受保护的单词,这并不能完全回答您想要做的事情,但有一种方法可以限制您的路线。我们在网站上有/用户名网址,我们使用了这样的约束。

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;