Search code examples
c#asp.netasp.net-web-api2asp.net-web-api-routing

ASP.net Web API attribute routing with int and string


This should be a quick one. I have two routes:

[HttpGet]
[Route("{id}")]
[ResponseType(typeof(Catalogue))]
public IHttpActionResult Get(string id) => Ok(_catalogueService.Get(id));

And

[HttpGet]
[Route("{numberOfResults:int}")]
[ResponseType(typeof(IEnumerable<Catalogue>))]
public IHttpActionResult List(bool active, int numberOfResults) => Ok(_catalogueService.List(active, numberOfResults));

When I use postman to try to List my catalogues , I pass something like this

/catalogues/10

And I expect it to go the the List method in my controller. Similarly, if I want to Get a catalogue, I pass something like this:

/catalogues/AB100

My routes were working, but I recently made a change to the List method (I added the active bool) and now my routes are not working properly. Both examples I gave above get captured by the Get method which is wrong.

Is there a way to fix this issue?


Solution

  • Add a default value for active and put it after numberOfResults parameter as an optional parameter.

    [HttpGet]
    [Route("{numberOfResults:int}")]
    [ResponseType(typeof(IEnumerable<Catalogue>))]
    public IHttpActionResult List(int numberOfResults, bool active = true) => //assuming active default
        Ok(_catalogueService.List(active, numberOfResults));
    

    Because of the additional required active parameter, it will no longer match the original overloaded route by default because it would be expecting active to be part of the URL even if not in the route template.

    Like

    /catalogues/10?active=true
    

    By making that parameter optional it means that it can now match the expected behavior as before with the active value provided to the action when omitted from the URL