So I'm putting together a proof of concept prototype for a WebAPI app, and all the usual methods work great. But I also wanted to demonstrate being able to call custom methods via WebAPI as well. So I have the following routing in my RouteConfig.cs:
routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); In the controller I have a simple method:
[HttpGet] public string Test() { return "this is a string"; } When I attempt to call my method : http://localhost:43225/api/values/test I get the following error in the brower:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"> The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'WebAPI_Listener.Controllers.ValuesController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. </string> But if I specify an ID at the end of the url, such as http://localhost:43225/api/values/test/1 it works, even though the method itself doesn't take a parameter at all.
So in the routing, if I have the id} set as optional, why doesn't it work when I don't specify an {id}, but does work if I do, even though the method itself isn't expecting an {id}??