Avrohom Yisroel
Avrohom Yisroel

Reputation: 9472

DELETE method not working

I have written a WebApi controller that contains the following method for deleting a client...

[HttpDelete]
public void DeleteClient(int id) {
  // do stuff here
}

...and am trying to test it by using the following HTML on a web page...

<form method="DELETE" action="/api/ClientsXml/">
  <table style="padding: 5px">
    <tr>
      <td>ID</td>
      <td><input type="text" size="20" name="id" id="id" /></td>
    </tr>
    <tr>
      <td> </td>
      <td><input type="submit" value="Send" /></td>
    </tr>
  </table>
</form>

However, the DeleteClient method is never called. It passes the request through to the GetClient method instead.

Anyone any idea why? I've tried all sorts of variations, but I just can't get the delete method called.

Upvotes: 1

Views: 541

Answers (2)

Simon C
Simon C

Reputation: 9508

@DimitryS's answer is correct, but I thought I'd build on it a little.

HTML forms only allow GET and POST operations. This is current in the HTML 5 spec as well as the HTML < 4 spec.

Other HTTP methods are allowed when using XMLHttpRequest which is what underlies jQuery's ajax functionality. So a good option could be to use jQuery for your PUTs, DELETEs, and it should work in all major browsers (some discussion of that in this pretty definitive SO question: Are the PUT, DELETE, HEAD, etc methods available in most web browsers?).

Lastly, I'll say that if you are just using the form to test your API, then why not try a browser extension instead: e.g.

There are many more, but most allow you to save a test suite, set different headers, and so forth.

Upvotes: 1

Dmitry S.
Dmitry S.

Reputation: 8513

Browsers usually can only perform GET or POST for the form elements (unless you are submitting it using AJAX).

You should change the form method to POST and add the following HTML element:

<input name="X-HTTP-Method-Override" type="hidden" value="DELETE" />

That is the way MVC allows to override HTTP methods for synchronous POSTs.

Edit: this post explains how to make the Web API support the same convention: https://stackoverflow.com/a/13135848/395359

Upvotes: 1

Related Questions