2011-09-16 14 views
8

Tôi muốn để lập bản đồ http://localhost/Guid-goes-here-ResellerController và lửa Index hoạt động của bộ điều khiển mà chỉ khi Guid-goes-herekhông trống Guid.Routing để điều khiển với một yêu cầu, không trống tham số Guid

bảng định tuyến của tôi trông như thế này:

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    routes.MapRoute(
     "Reseller", 
     "{id}", 
     new { controller = "Reseller", action = "Index", id = Guid.Empty } 
     // We can mark parameters as UrlParameter.Optional, but how to make it required? 
    ); 

    routes.MapRoute(
     "Default", // Route name 
     "{controller}/{action}/{id}", // URL with parameters 
     new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
    ); 

} 

Hành động trên ResellerController trông như thế này:

public ActionResult Index(Guid id) 
{ 
    // do some stuff with non-empty guid here 
} 

Một khi ứng dụng đã bắt đầu, điều hướng đến http://localhost đường tôi đến ResellerController với trống Guid làm đối số tham số id của hành động Index.

+0

Bạn có thể làm điều này với một hạn chế tuyến đường nhưng tôi khuyên bạn nên sử dụng các URL hợp lý hơn nếu bạn có thể để lộ trình cho người bán lại trông giống như '/ reseller/{guid}'. Ràng buộc tuyến đường sẽ phải phân tích cú pháp tất cả các yêu cầu HTTP để xem chúng có phải là GUID hợp lệ hay không. – Cymen

+0

@Cymen yes nhưng ommiting/reseller/octet từ url là bắt buộc trong kịch bản của tôi. – Dariusz

Trả lời

15
public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    routes.MapRoute(
     "Reseller", 
     "{id}", 
     new { controller = "Reseller", action = "Index", id = UrlParameter.Optional }, 
     new { id = @"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$" } 
    ); 

    routes.MapRoute(
     "Default", // Route name 
     "{controller}/{action}/{id}", // URL with parameters 
     new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
    ); 
} 

hoặc nếu bạn muốn có một hạn chế mạnh mẽ hơn một số regex khó hiểu:

public class GuidConstraint : IRouteConstraint 
{ 
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     var value = values[parameterName] as string; 
     Guid guid; 
     if (!string.IsNullOrEmpty(value) && Guid.TryParse(value, out guid)) 
     { 
      return true; 
     } 
     return false; 
    } 
} 

và sau đó:

routes.MapRoute(
    "Reseller", 
    "{id}", 
    new { controller = "Reseller", action = "Index", id = UrlParameter.Optional }, 
    new { id = new GuidConstraint() } 
);