带有自定义端点名称的WEB API .NET Action

时间:2016-12-22 14:36:14

标签: c# asp.net entity-framework asp.net-web-api

所以我在.NET中设置了一个后端,基本的HTTP调用正在运行。现在我需要一种替代方法,它不会通过ID搜索,而是通过属性搜索,所以我想在最后用不同的属性进行REST调用。

以下是我的控制器的两种方法:

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);
}

我的API配置配置如下:/api/{controller}/{action}/{id}

因此第一次通话适用于此次通话:/api/category/getcategory/2

当我尝试使用此调用的第二种方法时:/api/category/getcategorybyname/Jewelry

我收到错误消息,说我的控制器中没有任何操作符合请求。

这里有什么问题?

3 个答案:

答案 0 :(得分:3)

默认路由配置有一个可选参数,其约束类型为int。传递“珠宝”并不能满足这种限制。

最简单的解决方法是将RouteAttribute应用于操作并指定相应的参数。

[Route("api/category/getcategorybyname/{name}")]
public IHttpActionResult GetCategoryByName(string name)

确保您的WebConfig.cs文件已使用行

启用了属性路由
config.MapHttpAttributeRoutes();

您还可以通过将RouteAttribute应用于控制器,然后从操作的RoutePrefix("api/category")属性中剥离该部分来缩短Route中的操作名称。

答案 1 :(得分:2)

您还可以创建适用于控制器中所有操作的 RoutePrefix 规则,然后为每个操作应用特定的路由

(defn load-files [dir]
  (doseq [f (file-seq (File. dir))
          :when (.isFile f)]
    (load-file (.getAbsolutePath f))))

(load-files "utils")

答案 2 :(得分:1)

尝试使用Route属性

修饰第二个方法
[Route("GetCategoryByName")]

然后在浏览器中调用此名称。