In ASP.Net WebAPI does RouteParameter.Optional mea

2019-07-06 11:55发布

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.

2条回答
男人必须洒脱
2楼-- · 2019-07-06 12:10

You need to make the id a nullable int with a default of null

// doesn't work
public Product Get(int? id)
{
    return _svc.GetProduct(id);
}

// works
public Product Get(int? id = null)
{
    return _svc.GetProduct(id);
}

I'm about 95% sure both of these work under MVC (when declaring Optional for the route parameter), but Web API is stricter.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-06 12:27

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.

查看更多
登录 后发表回答