2012-09-17 17 views
1

說我有在Global.asax中類似於這樣的路線聲明:ASP.NET Web表單的路由,請檢查輸入類型

RouteTable.Routes.MapPageRoute("Products", "products/{productno}/{color}", "~/mypage.aspx");

如何配置路由所以只截取請求,如果{productno}是一個有效的Guid和{color}是一個整數值?

  • OK網址:/產品/ 2C764E60-1D62-4DDF-B93E-524E9DB079AC/123
  • 無效網址:/產品/ XXX/123

無效的網址將被被另一條規則/路線拾取或完全忽略。

回答

2

您可以通過實施匹配規則編寫自己的RouteConstraint。例如,這裏有一個確保的路由參數是一個有效日期:

public class DateTimeRouteConstraint : IRouteConstraint 
{ 
    public bool Match(System.Web.HttpContextBase httpContext, Route route, 
     string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
    { 
     DateTime dateTime; 
     return DateTime.TryParse(values[parameterName] as string, out dateTime); 
    } 
} 

然後你就可以通過改變路線定義(這是MVC 2.0)強制執行:

routes.MapRoute(
    "Edit", 
    "Edit/{effectiveDate}", 
    new { controller = "Edit", action = "Index" }, 
    new { effectiveDate = new Namespace.Mvc.DateTimeRouteConstraint() } 
); 

這裏一些更多資源:

  1. How can I create a route constraint of type System.Guid?
  2. http://prideparrot.com/blog/archive/2012/3/creating_custom_route_constraints_in_asp_net_mvc
+0

啊,這是我缺少的http://msdn.microsoft.com/en-us/library/system.web.routing.irouteconstraint(v=vs.100).aspx。 :)感謝指針... –

1

缺少創建自己的RouteConstraint標準路由系統支持標準語法中的RegEx路由約束。喜歡的東西:

string guidRegex = @"^(\{){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}$"; 
string intRegex = @"^([0-9]|[1-9][0-9]|[1-9][0-9][0-9])$"; 

routes.MapRoute(
    "Products", 
    "products/{productno}/{color}", 
    new { controller = "Products", action = "Index" }, 
    new { productno = guidRegex, color = intRegex } 
);