Search code examples
routesasp.net-web-api2attributerouting

Attributed Routing with multiple parameters in Web API 2


I am trying attributed routing with Web API 2. I have defined a route prefix and I have two methods. The first one works but the second one fails

[RoutePrefix("api/VolumeCap")]
public class VolumeCapController : ApiController
{            
        [Route("{id:int}")]
        public IEnumerable<CustomType> Get(int id)
        {
        }

        [Route("{id:int}/{parameter1:alpha}")]
            public CustomType Get(int id, string parameter1)
        {
        }
    }

http://localhost/MyWebAPI/api/VolumeCap/610023 //This works http://localhost/MyWebAPI/api/VolumeCap/610023?parameter1=SomeValue //This does not work

I get the following error

The requested resource does not support http method 'GET'.

I seem to be missing something obvious, but I am unable to figure out.


Solution

  • If you define a route with

    [RoutePrefix("api/VolumeCap")]
    

    and

    [Route("{id:int}/{parameter1:alpha}")]
    

    your url must look like this:

    api/VolumeCap/[IdValue]/[Parameter1Value]
    

    and not like this:

    api/VolumeCap/[IdValue]?parameter1=[Parameter1Value]
    

    Your url would match a method with this attribute [Route("{id:int}")], but with the additional parameter parameter1, i.e.

    [Route("{id:int}")]
    public IEnumerable<CustomType> Get(int id, string parameter1)
    

    This is because the first step to select an action is to match the route to the provided URL, which doesn't include the query string, but only the url segments (separated by /). Once the route is matched, the additional parameters are read from the query string, but only after the route matching.