user437899
user437899

Reputation: 9259

Web api routing: optional parameters

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?

Upvotes: 3

Views: 3055

Answers (1)

Rich Miller
Rich Miller

Reputation: 810

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.

Upvotes: 5

Related Questions