Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameter using Route attribute in web API?

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);
        }
like image 888
mshwf Avatar asked Dec 18 '22 08:12

mshwf


1 Answers

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();
 }
like image 99
Akos Nagy Avatar answered Jan 06 '23 01:01

Akos Nagy