Web api routing: optional parameters

3k views Asked by At

I have this route:

routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}/{myparam}",
                defaults: new { id = RouteParameter.Optional, myparam = RouteParameter.Optional }
            );

'id' should be optional and 'myparam' should be optional aswell but 'id' must not be optional if 'myparam' is set. How can I configure this?

1

There are 1 answers

0
Rich Miller On

I would guess that you will probably need to define two routes for this:

routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

routes.MapHttpRoute(
            name: "DefaultApiWithMyParam",
            routeTemplate: "api/{controller}/{id}/{myparam}"
        );

The first route will match all URLs whether or not they contain an ID, while the second will match URLs that contain values for both id and myparam. Note that no segments are optional in the second route.