I have the following routing rule:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"\d+"}
);
And a ProductController with these actions:
public Product Get(int id)
{
return _svc.GetProduct(id);
}
public int Post(Product p)
{
return 0;
}
I can call the Get
action as expected : GET "api/product/2"
I thought I'd be able to call my Post
action like this: POST "api/product"
but it doesn't work. I get a 404 error. It will work if I do this though: POST "api/product/2"
I thought by making the default value of id RouteParameter.Optional
that it meant that the {id} portion of the url did not need to be present to match the routing rule. But that doesn;t seem to be happening. Is the only way to make another rule that doesn't have the {id} part to the URL?
I'm slightly confused. Thanks for any help.
You need to make the
id
a nullable int with a default of nullI'm about 95% sure both of these work under MVC (when declaring Optional for the route parameter), but Web API is stricter.
I don't think it works as intended because you're adding a constraint to the id parameter. See this blog post http://james.boelen.ca/programming/webapi-routes-optional-parameters-constraints/ for the same scenario.