Can someone help me fill in the blanks with my GET methods for webapi. I want to pass in no parameters and get all results. Pass in an int and get a single result and pass in a named parameter to filter by a typeId / zoneId or both but am struggling to get this to work.
TimeController : ApiController
// Time/
//Time/1
//Time/typeId=1
//Time/zoneId=1
Time/typeId=1&zoneId=1
The closest I got was with
Global
RouteTable.Routes.MapHttpRoute(name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional}
);
RouteTable.Routes.MapHttpRoute(name: "TemplateTimeApi",
routeTemplate: "api/{controller}/{typeId}/{zoneId}",
defaults: new {typeId = RouteParameter.Optional, zoneId = RouteParameter.Optional }
);
Controller
List<TimeView> Get(int typeId, int? zoneId = null)
TimeView Get(int id)
but I get a 404 on no parameters.
I can change one of the parameters to a string if the issue is with two integers, however, I would prefer to understand the issue and get it to work.
If you take a look your routing table: the first routing is matched, but you don’t have action with no parameter => 404 thrown.
Run correct, the first route is matched, in here, it choose the action: TimeView Get(int id) becasue of the name: id on routing match to paramter "id" with this method. Remember, Web API bases heavily on naming convention.
Wrong URL => 404 thrown, I guess you would like to put as query string, should be: Time?typeId=1
But even wrong because, the first routing is match with parameter "Id", not "typeId", so no action method was found.
Wrong URL too, the same reason with above.
The correct URL you should have: GET Time/1/1 will match with your second route.
For more understanding on routing and action:
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection