Search code examples
routesasp.net-web-apiasp.net-web-api2

Web API Optional parameters in the middle


I have the following route mapping or WEB API

[Route("Foo/Id/{id=1}/bar")]

I want to make Id optional as above however from client side no matter what I call it route doesn't match and I get 404 I try things like

Foo/Id//bar

But doesn't work. Is there way to use optional parameters with web api if the parameter is not at the end?


Solution

  • You could not use // in URL. The only way to make things you want is to map 2 routes for one endpoint. For examle

    config.Routes.MapHttpRoute(
       name: "BarRoute",
       routeTemplate: "Foo/Id/{id}/bar",
       defaults: new { controller = "Foo" });
    
    config.Routes.MapHttpRoute(
       name: "BarDefaultRoute",
       routeTemplate: "Foo/Id/bar",
       defaults: new { controller = "Foo" });