Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

client.DeleteAsync - include object in body

I have an ASP.NET MVC 5 website - in C# client code I am using HttpClient.PutAsJsonAsync(path, myObject) fine to call a Json API (the API is also mine created in Web API).

client.BaseAddress = new Uri("http://mydomain");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PutAsJsonAsync("api/something", myObj);

I would like to do the same with a Delete verb. However client.DeleteAsync does not allow an object to be passed in the body. (I would like to record the reason for deletion alongside the Id of the item to delete in the URI).

Is there a way to do this?

like image 513
niico Avatar asked Mar 25 '17 16:03

niico


1 Answers

You'll have to give up a little in terms of convenience since the higher-level DeleteAsync doesn't support a body, but it's still pretty straightforward to do it the "long way":

var request = new HttpRequestMessage {
    Method = HttpMethod.Delete,
    RequestUri = new Uri("http://mydomain/api/something"),
    Content = new StringContent(JsonConvert.SerializeObject(myObj), Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);
like image 56
Todd Menier Avatar answered Nov 06 '22 13:11

Todd Menier