1

Global.asaxにこれに似たルート宣言があるとします。

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

{productno}が有効なGUIDで{color}あり、整数値である場合にのみリクエストをインターセプトするようにルートを構成するにはどうすればよいですか?

  • OK URL:/ products / 2C764E60-1D62-4DDF-B93E-524E9DB079AC / 123
  • 無効なURL:/ products / xxx / 123

無効なURLは、別のルール/ルートによって取得されるか、完全に無視されます。

4

2 に答える 2

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. System.Guidタイプのルート制約を作成するにはどうすればよいですか?
  2. http://prideparrot.com/blog/archive/2012/3/creating_custom_route_constraints_in_asp_net_mvc
于 2012-09-17T13:41:18.493 に答える
1

独自RouteConstraintの標準ルーティングシステムを作成する以外に、標準構文で正規表現ルート制約をサポートします。何かのようなもの:

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 }
);
于 2012-09-17T13:51:38.513 に答える