【问题标题】:Enumerating ASP.NET MVC RouteTable route URLs枚举 ASP.NET MVC RouteTable 路由 URL
【发布时间】:2010-12-14 18:28:10
【问题描述】:

我正在尝试弄清楚如何在RouteTable 中枚举Routes 的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

【问题讨论】:

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


    【解决方案1】:

    通过阻止用户注册受保护的字词,这并不能完全回答您想要做的事情,但是有一种方法可以限制您的路线。我们的网站中有 /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;
    

    【讨论】:

    • 在给定路由的 DataTokens 中添加一个“受保护的”布尔值并不是不合理的。不一定建议这样做,但管理起来不会特别困难。
    猜你喜欢
    • 2010-11-22
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    相关资源
    最近更新 更多