在 ASP.NET Web API REST 方法中使用特性路由






4.82/5 (7投票s)
如何将特性路由应用于 Web API 控制器
我的锯齿刀在哪里?
冒着显得过于激进或离题的风险,我在此断言,特性路由(大写是故意的)是自从切片面包以来最好的发明。
ASP.NET Web API REST 盛宴(及其兄弟姐妹)尽可能地使用约定优于配置。也就是说,你可以将控制器中的方法命名为 Get(某事),例如 GetAJob()
或 GetReal()
,HTTP GET
方法将调用它。
如果你有多个 Get
方法,只要它们具有唯一的签名,一切都很好。
但是,如果你有两个无参数的 Get
方法,例如一个用于获取项目计数(返回一个 int
),另一个用于获取所有项目(返回特定类型的集合)呢?
鸣响号角!(不是贝果,是号角!)
别怕——特性路由就在这里!
这里有一个例子,展示了两个没有参数的控制器 "GET"
方法
public int GetCountOfDuckbilledPlatypiRecords()
{
return _DuckbilledPlatypusRepository.GetCount();
}
public IEnumerable<duckbilledplatypus> GetAllDuckbilledPlatypi()
{
return _DuckbilledPlatypusRepository.GetAll();
}
如果我运行 Web API 应用程序并在浏览器中输入:“https://:28642/api/DuckbilledPlatypi”,我会让路由器感到困惑,它只能说
"Multiple actions were found that match the request: Int32 GetCountOfDuckbilledPlatypiRecords() on
type HandheldServer.Controllers.DuckbilledPlatypiController System.Collections.Generic.IEnumerable`1
[HandheldServer.Models.DuckbilledPlatypus] GetAllDuckbilledPlatypi() on type
HandheldServer.Controllers.DuckbilledPlatypiController"
但是,如果我添加特性路由,如下所示
[Route("api/DuckbilledPlatypi/Count")]
public int GetCountOfDuckbilledPlatypiRecords()
{
return _DuckbilledPlatypusRepository.GetCount();
}
[Route("api/DuckbilledPlatypi/GetAll")]
public IEnumerable<duckbilledplatypus> GetAllDuckbilledPlatypi()
{
return _DuckbilledPlatypusRepository.GetAll();
}
……然后输入“https://:28642/api/DuckbilledPlatypi/Count”,我得到 42(或者其他——取决于我拥有的鸭嘴兽数量,当然)。
如果我输入 https://:28642/api/DuckbilledPlatypi/GetAll,我得到,正如希望的那样,整个集合。
奶油和芥末骑兵
所以:当你的控制器需要不同的“查询”时,特性路由是救星!
注意: 新的更新(ASP.NET MVC 5.1)甚至改进了特性路由。请参阅 官方发布说明。
说到救援,如果你喜欢这个技巧,请务必慷慨地给为你提供服务的服务员小费。