我是这样解决这个问题的。
我使用 api 的 post 消息将整数列表作为数据发送。
然后我将数据作为 ienumerable 返回。
发送代码如下:
public override IEnumerable<Contact> Fill(IEnumerable<int> ids)
{
IEnumerable<Contact> result = null;
if (ids!=null&&ids.Count()>0)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:49520/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
String _endPoint = "api/" + typeof(Contact).Name + "/ListArray";
HttpResponseMessage response = client.PostAsJsonAsync<IEnumerable<int>>(_endPoint, ids).Result;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
result = JsonConvert.DeserializeObject<IEnumerable<Contact>>(response.Content.ReadAsStringAsync().Result);
}
}
}
catch (Exception)
{
}
}
return result;
}
接收代码如下:
// POST api/<controller>
[HttpPost]
[ActionName("ListArray")]
public IEnumerable<Contact> Post([FromBody]IEnumerable<int> ids)
{
IEnumerable<Contact> result = null;
if (ids != null && ids.Count() > 0)
{
return contactRepository.Fill(ids);
}
return result;
}
它适用于一条记录或多条记录。填充是使用 DapperExtensions 的重载方法:
public override IEnumerable<Contact> Fill(IEnumerable<int> ids)
{
IEnumerable<Contact> result = null;
if (ids != null && ids.Count() > 0)
{
using (IDbConnection dbConnection = ConnectionProvider.OpenConnection())
{
dbConnection.Open();
var predicate = Predicates.Field<Contact>(f => f.id, Operator.Eq, ids);
result = dbConnection.GetList<Contact>(predicate);
dbConnection.Close();
}
}
return result;
}
这允许您从复合表(id 列表)中获取数据,然后从目标表中返回您真正感兴趣的记录。
你可以对视图做同样的事情,但这会给你更多的控制和灵活性。
此外,查询字符串中不会显示您从数据库中查找的详细信息。您也不必从 csv 文件进行转换。
使用web api 2.x接口之类的任何工具时必须记住,get、put、post、delete、head等函数有通用用途,但不限于该用途.
因此,虽然 post 通常用于 web api 接口中的创建上下文,但它并不限于该用途。这是一个常规 html 调用,可用于 html 实践允许的任何目的。
此外,我们现在经常听到的那些“窥探的眼睛”隐藏了正在发生的事情的细节。
Web api 2.x 接口中命名约定的灵活性和常规 Web 调用的使用意味着您向 Web api 发送调用会误导窥探者认为您确实在做其他事情。例如,您可以使用“POST”来真正检索数据。