开发者

setting more than one RouteConstraint on route parameter

here are code I'm using to do, but compiler says: An anonymous type cannot have multiple properties with the same name

context.MapRoute("RouteNa开发者_如何学Gome", "statics/category/{fileName}",
                            new
                            {
                                controller = "myController",
                                action = "Index"
                            },
                            new
                            {
                                fileName = new fnRouteConstraint(),
                                fileName = new AnotherRouteConstraint()
                            });


Give the constraints names:

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


The error is pretty straightforward: you're creating an anonymous class with two properties that have the same name. It'd be the same as writing:

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

To fix the problem, you'll have to create another IRouteConstraint that contains the logic from the two constraints you're trying to pass. Example: http://nayyeri.net/custom-route-constraint-in-asp-net-mvc

EDIT:

If you want to "merge" two separate route constraints, you just need to create a third constraint like this:

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));
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜