2010-12-14 4 views
6

RouteTableRoutes의 URL을 열거하는 방법을 알아 내려고하고 있습니다. 내 사이트가 mysite.com, mysite.com/create이 PadController.CreateNote() 호출하는 경우, 즉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/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

사용자가 보호 된 단어를 등록하지 못하도록하고 싶지 않지만 경로를 제한 할 수있는 방법이 있습니다. 우리는/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'부울을 추가하는 것은 무리가되지 않습니다. 필연적으로 제안하는 것은 아니지만 관리가 특히 어렵지는 않습니다. –