在路由参数上设置多个RouteConstraint

时间:2010-06-19 06:56:55

标签: asp.net-mvc-2 constraints routes

这是我正在使用的代码,但编译器说:匿名类型不能有多个同名属性

context.MapRoute("RouteName", "statics/category/{fileName}",
                            new
                            {
                                controller = "myController",
                                action = "Index"
                            },
                            new
                            {
                                fileName = new fnRouteConstraint(),
                                fileName = new AnotherRouteConstraint()
                            });

2 个答案:

答案 0 :(得分:5)

给出约束名称:

        routes.MapRoute(
                   name: "app2",
                   url: "app/{id}",
                   defaults: new { controller = "App", action = "Index", id = UrlParameter.Optional },
                  constraints: new { RouteConstraint1 = new RouteConstraint1(),
                                     RouteConstraint2 = new RouteConstraint2() 
                                    }
               );

答案 1 :(得分:1)

错误非常简单:您正在创建一个具有两个具有相同名称的属性的匿名类。它和写作一样:

public class m {
    public string p { get; set; }
    public string p  { get; set; }
}

要解决此问题,您必须创建另一个IRouteConstraint,其中包含您尝试传递的两个约束中的逻辑。示例:http://nayyeri.net/custom-route-constraint-in-asp-net-mvc

编辑:

如果你想“合并”两个独立的路线约束,你只需要创建第三个约束:

public ThirdRouteConstraint: IRouteConstraint {
    public ThirdRouteConstraint(){}

    public bool Match(HttpContextBase httpContext, Route route,
        string parameterName, RouteValueDictionary values,
        RouteDirection routeDirection) 
    {
        return (new FirstRouteConstraint().Match(httpContext, route, parameterName, values, routeDirection) &&
            new SecondRouteConstraint().Match(httpContext, route, parameterName, values, routeDirection));
    }

}