这个问题本可以回答一百次,但我找不到合适的资源。在 WebApi 项目(VS 提供的默认项目)中,我有如下所示的 ValuesController。
public string Get(int id)
{
return "value";
}
[HttpGet]
public string FindByName(string name)
{
return name;
}
[HttpGet]
public string FindById(int id)
{
return id.ToString();
}
在 WebApiConfig.cs 中,我有以下路由映射。
config.Routes.MapHttpRoute(
name: "actionApiById",
routeTemplate: "api/{controller}/{action}/{Id}",
defaults: new { action = "FindById", Id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "actionApi",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: new { name = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
现在,当我在浏览器中尝试时,只有 FindById() 操作有效。为什么其余的 api 调用返回“找不到与请求匹配的 HTTP 资源”
如何让这三种方法都起作用?不使用 AttributeRouting。我是否缺乏 web api 的基本概念? (我想是的)
最佳答案
AS 我们都知道 REST 是基于资源的,它用 URL 标识资源,因此在 REST 服务中不允许使用超过一个具有相同参数的方法,但在 MVC 5 Web Api 方法级路由中有变通办法.
这是您可以执行此操作的示例:
[HttpGet]
[Route("api/search/FindByName/{name}")]
FindByName(string name)
{
}
[HttpGet]
[Route("api/search/FindById/{name}")]
FindById(int searchId)
注意:“search”为 Controller 名称。
如果需要更多说明,请告知。
关于asp.net-mvc-4 - 具有不同参数名称的 Web api 路由方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21593511/