27

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?

16
  • 1
    Can I know why you want to pass an Object in Delete method ? You can pass an Id in your URL Commented Mar 25, 2017 at 16:16
  • 1
    pass it as a parameter. and reconstruct your complex object model on the action Commented Mar 25, 2017 at 16:17
  • 1
    @niico take a look at some of the answers here. stackoverflow.com/questions/14323716/… Commented Mar 25, 2017 at 16:24
  • 1
    I am more partial to DELETE /api/path/{id}/{reason} but again (primarily opinion based) Commented Mar 25, 2017 at 16:25
  • 1
    A 3rd option to consider it is the query string. Putting it in the path violates REST in that it's not part of the resource's identity/location, so I would not do that. Since it's just a single string value, query string would be my first choice, body my second. Commented Mar 25, 2017 at 16:48

1 Answer 1

55

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);
Sign up to request clarification or add additional context in comments.

15 Comments

Thanks. Seems like using body in a DELETE is unconventional and therefore not a good idea though?!
Not typical but not unheard of. I got a request to accommodate it in my Flurl library not long ago.
Apparently RFC 7231 stipulates: "DELETE - No defined body semantics." - seems a bad idea going against standards no?
Where in the spec did you see that? I'm looking at it right now and I don't see that anywhere.
I would but that wouldn't answer the question you asked. This one does, which is more useful to others who find it via search. If the querystring suggestion was helpful, cool, I don't need points for it. :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.