Sadegh
Sadegh

Reputation: 4341

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("RouteName", "statics/category/{fileName}",
                            new
                            {
                                controller = "myController",
                                action = "Index"
                            },
                            new
                            {
                                fileName = new fnRouteConstraint(),
                                fileName = new AnotherRouteConstraint()
                            });

Upvotes: 0

Views: 1953

Answers (2)

Mr. Flibble
Mr. Flibble

Reputation: 27023

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

Upvotes: 5

Evan Nagle
Evan Nagle

Reputation: 5133

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

}

Upvotes: 1

Related Questions