5

I want two patterns of API url point to the same API action method:

api/Cities/{countryCode}

and

api/Cities

Is this possible to configure using Route attribute?

I made this and didn't work:

   [HttpGet, Route("GetCities/{code?}")]
        public dynamic GetCities(string code)
        {
            return GENOrderRepository.SelectCities(Context, code);
        }
mshwf
  • 7,009
  • 12
  • 59
  • 133
  • Possible duplicate of [Attribute routing with optional parameters in ASP.NET Web API](http://stackoverflow.com/questions/22388452/attribute-routing-with-optional-parameters-in-asp-net-web-api) – The Bearded Llama Mar 20 '17 at 17:13

1 Answers1

14

Just create one action method, and use the route attribute like this:

Route[("api/Cities/{countryCode?}")]

(Note the question mark at the end, that makes a parameter optional). You also have to supply a default parameter to the parameter. See my working sample:

 [HttpGet, Route("GetCities/{code?}")]
 public IHttpActionResult GetCities(string code=null)
 {
     return Ok();
 }
Akos Nagy
  • 4,201
  • 1
  • 20
  • 37
  • Please see the amended question – mshwf Mar 20 '17 at 15:04
  • Thanks for the sample. This shows that you have left out the default parameter from the action method. Please check my edit in the answer. – Akos Nagy Mar 20 '17 at 15:09
  • I see it used like: `num:int?` what is this? – mshwf Mar 20 '17 at 15:12
  • That specifies the url parameter `num` as an optional integer (`:int` for the integer and `?` for the optional). By default url parameters are __usually__ treated as strings. – Akos Nagy Mar 20 '17 at 15:18