问题描述
我们有一个以DotNet Core 3.1.402(我是DotNet Core和WebAPI的新手)编写的Web API。
我们有一个具有AccountID,AccountName,AccountNumber等的帐户模型。
我们希望通过不同的属性来获得一个帐户,例如:通过AccountID,通过AccountName,通过AccountNumber。
我们如何做到这一点,以便我们不需要为每个属性使用单独的HttpGet(因此我们不必为不同的属性重复相同的代码)?
这是AccountsController中的HttpGet,用于通过AccountID获取帐户
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;
}
这是“帐户”类别
namespace MyApi.Models
{
public class Account
{
public string AccountID { get; set; }
public string AccountName { get; set; }
public string AccountNumber { get; set; }
// other attributes
}
}
谢谢。
解决方法
使用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" }
]