C# 使用System.Net.Http调用Delete Web API方法时传递正文内容
我有一个场景需要调用我的Web API Delete方法,构造如下:C# 使用System.Net.Http调用Delete Web API方法时传递正文内容,c#,http,asp.net-web-api,system.net.httpwebrequest,C#,Http,Asp.net Web Api,System.net.httpwebrequest,我有一个场景需要调用我的Web API Delete方法,构造如下: // DELETE: api/products/{id}/headers [HttpDelete("{id}/headers")] public void DeleteProductHeaders(int id, [FromBody] string query) { } 诀窍在于,为了获得查询,我需要通过body发送它,deleteAscync不像post那样有json的参数。有人知道我如何在c#中使用System.Net.
// DELETE: api/products/{id}/headers
[HttpDelete("{id}/headers")]
public void DeleteProductHeaders(int id, [FromBody] string query)
{
}
诀窍在于,为了获得查询,我需要通过body发送它,deleteAscync不像post那样有json的参数。有人知道我如何在c#中使用System.Net.Http客户端来实现这一点吗
我认为,HttpClient采用这种设计方式的原因是,尽管HTTP 1.1规范允许在请求上使用消息体,但本质上它不应该这样做,因为规范没有按照定义为它定义任何语义。HttpClient严格遵循HTTP规范,因此您可以看到它不允许您向请求中添加消息体 因此,我认为客户端的选项包括使用中描述的HttpRequestMessage。如果您想从后端修复它,并且如果您的消息体在查询参数中工作良好,您可以尝试这样做,而不是在消息体中发送查询 我个人认为应该允许DELETE有一个消息体,并且不应该在服务器中被忽略,因为肯定有类似于您在这里提到的那样的用例
在任何情况下,关于这一点的更富有成效的讨论,请看。以下是我是如何完成的
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);
我的API如下所示:
// DELETE api/values
public void Delete([FromBody]string value)
{
}
从C#服务器端呼叫
string URL = "http://localhost:xxxxx/api/values";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "DELETE";
request.ContentType = "application/json";
string data = Newtonsoft.Json.JsonConvert.SerializeObject("your body parameter value");
request.ContentLength = data.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Write(data);
requestWriter.Close();
try
{
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
}
catch
{
}
您可以尝试使用DELETE方法和
HttpContent
手动创建HttpRequestMessage
,然后使用HttpClient.sendsync
string URL = "http://localhost:xxxxx/api/values";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "DELETE";
request.ContentType = "application/json";
string data = Newtonsoft.Json.JsonConvert.SerializeObject("your body parameter value");
request.ContentLength = data.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Write(data);
requestWriter.Close();
try
{
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
}
catch
{
}