Trying to set up a new site using MVC RC4 web API in Visual Studio 2010, and it just seems to not work: parameter values are never passed to the method.
As far as I can tell I have done everything exactly as described here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
Route configuration:
routes.Clear();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new {
id = RouteParameter.Optional
}
);
Below is the regular MVC route, I’ve also tried just removing this entirely to see if there
was some conflict but it made no difference.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
Test controller:
public class TestController : ApiController
{
[HttpGet]
public int Double(int value)
{
return value * 2;
}
}
URL: http://localhost:1505/api/test/double/4
The parameters dictionary contains a null entry for parameter 'value' of
non-nullable type 'System.Int32' for method 'Int32 Double(Int32)' in
'MyAppName.Controllers.TestController'. An optional parameter must be a
reference type, a nullable type, or be declared as an optional parameter.
Argh. This is about as simple as it gets isn’t it? But nothing seems to result in the parameter being mapped. For the heck of it I also tried
http://localhost:1505/api/test/double?id=4
No difference. If I make the parameter accept null values, e.g.
public int Double(int? value)
it runs, but value is always null.
What am I doing wrong?
In your route you have
{id}but in your action you havevalueand MVC matches the “things” (route values, query string values etc.) by name.So the names should align:
So change your routing to :
And it will work with the URL:
http://localhost:1505/api/test/double/4Note: if you leave the
valueRouteParameter.Optionalyou need to change type in your action’s signature toint?.Or you can change your action method signature:
Or you can leave it as it is just use this URL:
http://localhost:1505/api/test/double?value=4