Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

c# - Passing body content when calling a Delete Web API method using System.Net.Http

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...