【问题标题】:WebAPI - how do I "overload" the GET method?WebAPI - 我如何“重载” GET 方法?
【发布时间】:2016-10-03 16:33:39
【问题描述】:

所以我是 ASP.NET webAPI 的新手,我创建了一个名为:UsersController 的控制器,它公开了 4 个 CRUD 方法。 如果用户调用:

获取/用户

  • 这将使用默认的Get方法

    公共 IEnumerable Get()

如果用户调用:

GET /users/1234

  • 这反过来会调用:

    公共字符串获取(int id)

但是... 如果我需要类似的东西怎么办:

GET / 用户/男性

  • 我要退回所有男性用户 和

GET /Users/Tall

  • 我想退回所有 Tall 用户

如何覆盖/重载 GET 方法?

【问题讨论】:

    标签: asp.net-web-api


    【解决方案1】:

    使用路由属性。

    在您的 Api 控制器中:

    public IEnumerable Get()
    {
    }
    
    public string Get(int id)
    {
    }
    
    [Route("/Users/Tall")]
    public IEnumerable GetTall()
    {
    }
    

    更多信息:http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

    【讨论】:

    • 我在哪里添加这个?我的 ApiController 没有属性
    • 在您的 GetTall() 方法中使用该属性。查看更新后的答案。
    • 我收到以下错误:参数字典包含非可空类型 'System.Int32' 的参数 'id' 的空条目,用于方法 'System.String Get(Int32)' in ' RESTServices.Controllers.recordsController'。可选参数必须是引用类型、可空类型或声明为可选参数。
    • 它是一个空控制器,不管是 ASP.NET webapi 的默认值。
    • 可能您正在调用 Get(int id) 方法而不传递整数值。调用应该类似于“localhost/records/123”,其中 123 是一个 id。
    【解决方案2】:

    请看这里:https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

    路由约束 路由约束允许您限制路由模板中的参数如何匹配。一般语法是“{parameter:constraint}”。例如:

    [Route("users/{id:int}")]
    public User GetUserById(int id) { ... }
    
    Route("users/{name}")]
    public User GetUserByName(string name) { ... }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      相关资源
      最近更新 更多