Question

I am using the default routing setup in WebApiConfig (MVC 4) but for some reason I am getting unexpected results.

If I call /api/devices/get/ it hits the Get function but the Id is "get" rather than 1. If I call /api/devices/get/1 I get a 404. I also want to be able to support multiple parameters i.e.

public Device[] Get(int? page, int? pageSize) // for multiple devices

The route

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional });
}

And my API:

public class DevicesController : ApiController
{
    EClient client = new EClient();

    // GET api/devices/5
    public Device Get(string id)
    {
        return client.GetDeviceBySerial(id);
    }
}
Was it helpful?

Solution

id in the controller parameter should be integer:

public Device Get(int id)
{
    return client.GetDeviceBySerial(id);
}

if you need to pass in string, or other prams, just use quesry string:

public Device Get(int id, string pageSize)
{
    return client.GetDeviceBySerial(id);
}

the above can be called as:

/api/devices/1

or

/api/devices/?id=1&pageSize=10

Note: you do not need to specify method name. Web API will judge that on the basis of HTTP Verb used. If its a GET request, it will use the Get method, if its a POST request, then it will use Post method ... and so on.

You can change the above behavior, but I guess you mentioned that you want to keep usign the default Routing ... so I am not covering that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top