In an ASP.NET Web API I have modified the default GET action to accept an optional parameter which will declare the depth at which to get the Object:
public ObjectModel Get(int id, int? loadType = 1)
{
if (loadType.Value == 1)
{
return GetDeepObjectModel(id);
}
else
{
return GetShallowObjectModel(id);
}
}
Given the default route:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"\d+" }
);
I have an issue with valid requests in that:
https://www.mysite.com/api/objects/1234?loadType=1
will work, but I would also like this same action to work for the basic get – considering the loadType param as optional:
https://www.mysite.com/api/objects/1234
With the second request, I get a 404 not found. It seems that the id is not getting counted as a matched variable when it is paired with an optional param.
Is there something I am missing here? I would very much not to start adding new routes to cover this issue, since my experience with MVC has told me that adding routes can get out of hand very quickly.
I can’t be entirely sure of this, but it seems the default value on my
parameter is causing the issue. If I change the default value to null
And check in the action for setting the default value
both versions of the request are properly directed to the intended action.