枚举 ASP.NET MVC RouteTable 路由 URL

6

我正在尝试找出如何枚举RouteTableRoutes的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

1个回答

5

这并没有完全回答你想要做的事情,即防止用户注册受保护的词汇,但是你可以通过约束路由来实现。我们网站上有/username的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中添加一个“protected”布尔值并不是不合理的。虽然不一定建议这样做,但管理起来并不特别困难。 - Nathan Taylor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接