C# webAPI restrict route
在webapi项目的WebAPIConfig.cs中,添加了2条路由
1 2 3 4 5 6 7 8 9 10 11 |
我尝试创建一个包含以下功能的apiController
1 2 3 4 5 6 7 8 9 10 11 | [HttpGet] public string Get(int id) { return"get"; } [HttpGet] [ActionName("ByWait")] public string[] ByWait(int id) { return"bywait"; } |
我希望
请求/ api / controllername / 1234返回" get ",并且
请求/ api / controllername / bywait / 1234返回" bywait "。
但是,实际结果是
/ api / controllername / 1234 >>引发异常找到多个与请求匹配的动作
/ api / controllername / bywait / 1234 >> " by wait "
但是可以解决此问题吗?
s.t如何限制功能ByWait仅接受包含操作的请求,以使其仅响应/ api / controllername / bywait / 1234而忽略/ api / controllername / 1234
还是有其他更好的解决方案?
谢谢
首先,您可以更改WebApiConfig:
1 2 3 4 5 6 7 8 9 10 | config.Routes.MapHttpRoute( name:"ActionApi", routeTemplate:"api/{controller}/{action}/{id}" ); config.Routes.MapHttpRoute( name:"DefaultApi", routeTemplate:"api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); |
然后控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | [HttpGet] public string Get() { return"get-default"; } [HttpGet] public string Get(int id) { return"get" + id; } [HttpGet] [Route("api/values/bywait/{id}")] public string ByWait(int id) { return"bywait"; } |