【问题标题】:Web API HTTPGet for multiple attributes?Web API HTTPGet 用于多个属性?
【发布时间】:2020-10-15 19:49:15
【问题描述】:

我们有一个用 DotNet Core 3.1.402 编写的 Web API(我是 DotNet Core 和 WebAPI 的新手)。

我们使用 SqlKata 进行数据库处理。

我们有一个 Account 模型,其中包含 AccountID、AccountName、AccountNumber 等。

我们希望通过不同的属性获取一个帐户,例如:通过 AccountID、通过 AccountName、通过 AccountNumber。

我们如何做到这一点,以便我们不需要为每个属性单独的 HttpGet(这样我们就不必为不同的属性重复相同的代码)?

这是我们在AccountsController中通过AccountID获取帐号的HttpGet

public class AccountsController : ControllerBase
{
    private readonly IAccountRepository _accountRepository;

    [HttpGet("{AccountID}")]
    public Account GetAccount(int AccountID)
    {
        var result = _accountRepository.GetAccount(AccountID);
        return result;
    }

这是 AccountRepository.cs 中的代码

public Account GetAccount(int accountID)
{
  var result = _db.Query("MyAccountTable").Where("AccountID", accountID).FirstOrDefault<Account>();
  return result;
}

这是 Account 类

namespace MyApi.Models
{
   public class Account
   {
       public string AccountID { get; set; }
       public string AccountName { get; set; }
       public string AccountNumber  { get; set; }
       // other attributes
   }
 }

谢谢。

【问题讨论】:

    标签: c# asp.net-web-api .net-core asp.net-core-webapi http-get


    【解决方案1】:

    使用 GET 可能会很痛苦,有一些方法可以传递路径/查询数组和复杂对象,但是很难看,最好的方法是使用 POST 而不是 GET 并传递带有过滤器的对象你想要的。

    //In the controller...
    [HttpPost]
    public Account GetAccount([FromBody]Filter[] DesiredFilters)
    {
        var result = _accountRepository.GetAccount(DesiredFilters);
        return result;
    }
    
    //Somewhere else, in a shared model...
    public class Filter
    {
        public string PropertyName { get; set; }
        public string Value { get; set; }
    }
    
    //In the repository...
    public Account GetAccount(Filter[] Filters)
    {
        var query = _db.Query("MyAccountTable");
    
        foreach(var filter in Filters)
            query = query.Where(filter.PropertyName, filter.Value);
    
        return query.FirstOrDefault<Account>();
    }
    

    现在,您可以在请求正文中发送一个 JSON 数组,其中包含您想要的任何过滤器,例如:

    [ 
        { "PropertyName": "AccountID", "Value": "3" }, 
        { "PropertyName": "AccountName", "Value": "Whatever" }
    ]
    

    【讨论】:

    • 行得通!非常感谢您的快速回复!
    猜你喜欢
    • 2017-01-30
    • 2021-11-08
    • 1970-01-01
    • 2013-07-14
    • 2017-06-26
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多