CHS*_*CHS 3 asp.net-mvc asp.net-web-api
我有以下路由规则:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"\d+"}
);
Run Code Online (Sandbox Code Playgroud)
以及具有以下操作的ProductController:
public Product Get(int id)
{
return _svc.GetProduct(id);
}
public int Post(Product p)
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我可以Get按预期方式调用该操作:GET“ api / product / 2”
我以为我可以这样调用我的Post操作:POST“ api / product”,
但是它不起作用。我收到404错误。如果我这样做,它将起作用:POST“ api / product / 2”
我认为通过设置id的默认值RouteParameter.Optional,就意味着不需要显示url的{id}部分来匹配路由规则。但这似乎没有发生。制定另一条不包含URL的{id}部分的规则的唯一方法是吗?
我有点困惑。谢谢你的帮助。
您需要将id一个可为null的 int 设置为默认值null
// doesn't work
public Product Get(int? id)
{
return _svc.GetProduct(id);
}
// works
public Product Get(int? id = null)
{
return _svc.GetProduct(id);
}
Run Code Online (Sandbox Code Playgroud)
我大约95%的人都确定这两种方法都可以在MVC下工作(当为route参数声明Optional时),但是Web API更为严格。
| 归档时间: |
|
| 查看次数: |
5690 次 |
| 最近记录: |