12

我有一个场景,我需要调用构造如下的 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;
}
4

3 回答 3

26

这是我如何完成它

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);
于 2017-10-16T23:41:38.060 回答
2

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

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

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

无论如何,如果要对此进行更富有成效的讨论,请查看内容。

于 2016-08-16T14:08:44.530 回答
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
            {

            }
于 2018-07-06T08:56:25.150 回答