HttpClient的WebAPI删除列表 [英] WebAPI delete list by HttpClient
问题描述
在我的WebApi中,我想让方法witch接受ID列表作为参数并将其全部删除.因此,该方法类似于下面的代码.
In my WebApi I want to have method witch accepts ID list as parameter and deletes them all. So this method looks like code below.
[HttpDelete]
public IHttpActionResult DeleteList([FromBody]IEnumerable<int> templateIds)
我还需要使用.NET的HttpClient为此编写单元测试. 所以我的问题是:如何使用HttpClient DeleteAsync将ID的数组/列表传递给WebApi?
I also need Unit Test to be written for this using .NET's HttpClient. So my question is: how can I pass array/list of Ids to WebApi using HttpClient DeleteAsync?
:)
推荐答案
据我所知,在Web Api中将忽略在HTTP DELETE中发送消息正文.另一种方法是从Uri中获取ID列表:
As far as I am aware sending a message body in a HTTP DELETE is ignored in Web Api. An alternative is to take in the list of Ids from the Uri:
[HttpDelete]
public void DeleteList([FromUri]IEnumerable<int> ids)
然后使用以下网址调用网址:http://server/api/ControllerRoute/ids=1&ids=2
then call the url with: http://server/api/ControllerRoute/ids=1&ids=2
要从HttpClient调用此方法,您将直接进行DeleteAsync,因为所有数据都位于Url中.
To call this from HttpClient, you'd make the DeleteAsync directly because all of the data is in the Url.
您还可以分解System.Web.HttpUtility为您在Url中构建查询字符串,如下所示:
You could also break out System.Web.HttpUtility to build the query string in the Url for you, like so:
var httpClient = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
foreach (var id in ids)
{
queryString.Add("ids", id.ToString());
}
var response = httpClient.DeleteAsync(queryString.ToString());
这篇关于HttpClient的WebAPI删除列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!