【问题标题】:Passing body content when calling a Delete Web API method using System.Net.Http使用 System.Net.Http 调用 Delete Web API 方法时传递正文内容
【发布时间】:2026-02-07 13:05:01
【问题描述】:

我有一个场景,我需要调用我的 Web API Delete 方法,构造如下:

// DELETE: api/products/{id}/headers
[HttpDelete("{id}/headers")]
public void DeleteProductHeaders(int id, [FromBody] string query)
{
}

诀窍是,为了得到查询,我需要通过正文发送它,而 DeleteAsync 没有像 post 那样的 json 参数。有谁知道我如何在 c# 中使用 System.Net.Http 客户端来做到这一点?

// 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;
}

【问题讨论】:

  • 您可以尝试使用 DELETE 方法和HttpContent 手动创建HttpRequestMessage,然后使用HttpClient.SendAsync

标签: c# http asp.net-web-api system.net.httpwebrequest


【解决方案1】:

我的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
            {

            }

【讨论】:

    【解决方案2】:

    我是这样完成的

    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);
    

    【讨论】:

      【解决方案3】:

      我认为 HttpClient 采用这种方式设计的原因是尽管 HTTP 1.1 规范允许 DELETE 请求上的消息正文,但本质上它不应该这样做,因为规范没有为它定义任何语义,因为它定义了 @ 987654322@。 HttpClient 严格遵循 HTTP 规范,因此您会看到它不允许您向请求添加消息正文。

      所以,我认为您在客户端的选择包括使用here 中描述的 HttpRequestMessage。如果您想从后端修复它,并且如果您的消息正文在查询参数中运行良好,您可以尝试这样做,而不是在消息正文中发送查询。

      我个人认为 DELETE 应该被允许有一个消息正文并且不应该在服务器中被忽略,因为肯定有像你在这里提到的那样的用例。

      在任何情况下,如果要对此进行更富有成效的讨论,请查看this

      【讨论】: