6

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);
        }
1

1 Answer 1

15

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();
 }
Sign up to request clarification or add additional context in comments.

4 Comments

Please see the amended question
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.
I see it used like: num:int? what is this?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.