Passing body content when calling a Delete Web API

2020-04-05 07:16发布

问题:

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)
{
}

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

回答1:

Here is how I accomplished it

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


回答2:

I think the reason HttpClient is designed that way is although HTTP 1.1 spec allows message body on DELETE requests, essentially it is not expected to do so as the spec doesn't define any semantics for it as it is defined here. HttpClient strictly follows HTTP spec thus you see it doesn't allow you to add a message body to the request.

So, I think your option from the client side includes using HttpRequestMessage described in here. If you want to fix it from the backend and if your message body would work well in query params you can try that instead of sending the query in message body.

I personally think DELETE should be allowed to have a message body and should not be ignored in a server as there are certainly use cases for that like the one you mentioned here.

In any case for more productive discussion on this please have a look at this.



回答3:

My API as below:

// DELETE api/values
public void Delete([FromBody]string value)
{
}

Calling from C# server side

            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
            {

            }