【问题标题】:Web Api already defines a member called 'Get' with the same parameter typesWeb Api 已经定义了一个名为“Get”的成员,具有相同的参数类型
【发布时间】:2014-03-20 01:17:14
【问题描述】:
public class UsersController : ApiController
{
    // GET api/companies/{company_id}/users/{user_id}
    public object Get(int company_id, int user_id)
    {
       ...
    }

    // GET api/companies/{company_id}/plants/{plant_id}/users
    public IEnumerable<object> Get(int company_id, int plant_id)
    {
       ...
    }
}

第一种方法应该返回公司的单个用户部分 第二种方法应该返回一个公司和工厂的用户列表

错误类型“...”已经定义了一个名为“Get”的成员,具有相同的参数类型

是否可以避免 Web Api 将第二个 Get 解释为重定义?

如果看过http://aspnetwebstack.codeplex.com/wikipage?title=Attribute%20routing%20in%20Web%20API 在场景 3 中使用 [HttpGet("...")]notations

public class MoviesController : ApiController
{
    [HttpGet("actors/{actorId}/movies")]
    public Movie Get(int actorId) { }
    [HttpGet("directors/{directorId}/movies")]
    public Movie Get(int directorId) { }
}

但就我而言 [HttpGet(...)] 错误 'System.Web.Http.HttpGetAttribute' 不包含带 1 个参数的构造函数

【问题讨论】:

  • 这不是“web api”抱怨。应该是 C# 编译器在抱怨。在同一个类中,不能有两个具有相同名称、具有相同参数类型的方法。返回类型在重载决议中没有任何作用。
  • (那个场景 3 的例子似乎也是错误的,原因完全一样,正如文章下方的第一条评论所指出的那样)
  • 我希望让 C# 知道它们实际上是两种不同的重载方法。

标签: c# asp.net asp.net-mvc asp.net-web-api


【解决方案1】:

我认为你必须命名你的 get 函数:

public class UsersController : ApiController
{
    // GET api/companies/GetByUser/{company_id}/{user_id}
    public object GetByUser(int company_id, int user_id)
    {
       ...
    }

    // GET api/companies/GetByPlanet/{company_id}/{plant_id}
    public IEnumerable<object> GetByPlanet(int company_id, int plant_id)
    {
       ...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 2022-12-11
    相关资源
    最近更新 更多