Search code examples
asp.netasp.net-coreurl-routing

How can i perform routing with multiple Ids in asp.net core 3.1


How can i perform routing with below URLs

I have following types of URLs

  1. api/country It will return all country
  2. api/country/1 It will return specific country
  3. api/country/1/state it will return all state of country 1
  4. api/country/1/state/1 it will return specific state of specific country
  5. api/country/1/state/1/city it will return all city of state 1 country 1
  6. api/country/1/state/1/city/1 it will return specific city of state 1 country 1

Solution

  • Your route parameter does not have to say "id". You can pick any variable name. For instance:

    [HttpGet("api/country/{countryId}/state/{stateId}/city/{cityId")]
    public IActionResult GetCity(
            [FromRoute]int countryId, [FromRoute]int stateId, [FromRoute]int cityId)
    {
        // pick what you want to return here
    }
    

    If you use the [ApiController] on your controller class, you wouldn't have to use [FromRoute] on every attribute.