使用System.Net.Http调用Delete Web API方法时传递正文内容 [英] Passing body content when calling a Delete Web API method using System.Net.Http
本文介绍了使用System.Net.Http调用Delete Web API方法时传递正文内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个需要调用如下构造的Web API Delete方法的场景:
I have a scenario where I need to call my Web API Delete method constructed like the following:
// DELETE: api/products/{id}/headers
[HttpDelete("{id}/headers")]
public void DeleteProductHeaders(int id, [FromBody] string query)
{
}
诀窍在于,为了获得查询,我需要通过正文发送查询,而DeleteAsync与post一样没有json的参数.有谁知道我如何使用C#中的System.Net.Http客户端来做到这一点?
The trick is that in order to get the query over I need to send it through the body and DeleteAsync does not have a param for json like post does. Does anyone know how I can do this using System.Net.Http client in c#?
// Delete a product's headers
public void DeleteProductHeaders(int id, string query)
{
using (var client = GetClient())
{
HttpResponseMessage response;
try
{
// HTTP DELETE
response = client.DeleteAsync($"api/products/{id}/headers").Result;
}
catch (Exception ex)
{
throw new Exception("Unable to connect to the server", ex);
}
}
return retVal;
}
推荐答案
这是我的实现方法
var request = new HttpRequestMessage(HttpMethod.Delete, "http://www.example.com/");
request.Content = new StringContent(JsonConvert.SerializeObject(object), Encoding.UTF8, "application/json");
await this.client.SendAsync(request);
这篇关于使用System.Net.Http调用Delete Web API方法时传递正文内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文