Tan*_*uyB 4 c# asp.net entity-framework asp.net-web-api
因此,我已经在.NET中设置了一个后端,并且基本的HTTP调用正在工作。现在,我需要一个替代方法,该方法将不按ID搜索而是按属性搜索,因此我想在结尾处进行具有其他属性的REST调用。
这是我的控制器的2种方法:
public IHttpActionResult GetCategory(int id)
{
var category = _productService.GetCategoryById(id);
if (category == null) return NotFound();
var dto = CategoryToDto(category);
return Ok(dto);
}
public IHttpActionResult GetCategoryByName(string name)
{
var category = _productService.GetCategoryByName(name);
if(category == null) return NotFound();
var dto = CategoryToDto(category);
return Ok(dto);
}
Run Code Online (Sandbox Code Playgroud)
我的API配置配置如下:/api/{controller}/{action}/{id}。
因此,第一个呼叫可与此呼叫一起使用: /api/category/getcategory/2
当我通过此调用尝试第二种方法时: /api/category/getcategorybyname/Jewelry
我收到一条错误消息,说控制器中没有任何动作与请求匹配。
这是什么问题
默认的路由配置具有一个可选参数,其约束类型为int。传递“珠宝”不满足该约束。
最简单的解决方法是将RouteAttribute应用于操作并以这种方式指定参数。
[Route("api/category/getcategorybyname/{name}")]
public IHttpActionResult GetCategoryByName(string name)
Run Code Online (Sandbox Code Playgroud)
确保您的WebConfig.cs文件已启用带有行的属性路由
config.MapHttpAttributeRoutes();
Run Code Online (Sandbox Code Playgroud)
您也可以RouteAttribute通过将a RoutePrefix("api/category")应用于控制器,然后从操作的Route属性中删除该部分来缩短操作名称。