c# - WebAPI Controller GetAll 或 Get some Id

标签 c# asp.net-web-api asp.net-web-api2 asp.net-web-api-routing

我有一个这样的 Controller

[Route("api/Foo/MyController/{id}")]
public IHttpActionResult Get(int id)
{
   //Code code
   foo(id); // Foo accept Int or Null
}

这确实有效,如果调用 api/Foo/MyController/1,但我需要调用 api/Foo/MyController 就像它“GetAll”参数 id 现在是null 和 stuff into controller 返回所有,怎么去那里?

最佳答案

你可以添加一个新的方法和路由:

[Route("api/Foo/MyController")]
public IHttpActionResult Get()
{
   //Code code
}

编辑:要重用您可以使用可选参数的相同方法:

    [Route("api/Foo/MyController/{id}")]
    public IHttpActionResult Get(int? id)
    {
        if (id.HasValue)
        {
           // get by id
        } 
        else
        {
           // get all
        }
    }

关于c# - WebAPI Controller GetAll 或 Get some Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45314108/

相关文章:

c# - Java GUI 中的 C# gridview 是什么?

c# - 如何使用C#获取注册的.NET组件的位置?

c# - 使用 json 数组和 json 对象的优缺点

javascript - 在 vuejs (axios) 和 web api 中加载图像

asp.net-mvc - 适用于多个项目的单一 ASP.NET 身份

javascript - "The requested resource does not support http method ' POST' - 405 响应

c# - 错过的垃圾收集通知

c# - 解析 UWP 应用中的当前用户

c# - .Net Web Api不显示必需属性的错误消息

c# - Web API - 检测空赋值