views:

30

answers:

1

How can I detect at the startup of the application that a client doesn't support DELETE and PUT verbs and automatically overload the POST verb?
On the server side, how can I redirect those overloaded POST verbs into the right actions?
Say I have a DELETE request that is overriden, how do I call the appropriate function in the controller that matches the action?
My guess is that I should use some action filter and use reflection to inspect the attributes that matches my function (in this example: DeleteFoo(Guid Id)).

+5  A: 

You cannot detect whether a client supports or not those verbs. Also for browsers that do not support PUT and DELETE verbs in html forms you could use the HttpMethodOverride helper inside your form which will add a hidden field to the form which will instruct the runtime to invoke the proper controller action despite the fact that under the covers a POST request is sent.

<% using (Html.BeginForm("Destroy", "Products", new { id = "123" }, FormMethod.Post)) { %>
    <%: Html.HttpMethodOverride(HttpVerbs.Delete) %>
    <input type="submit" value="Delete" />
<% } %>

which will call the action decorated with [HttpDelete]:

[HttpDelete]
public ActionResult Destroy(int id)
{
    // TODO: delete product
    TempData["message"] = "product deleted";
    return RedirectToAction("index");    
}

The important thing here is that a controller shouldn't care or depend about what verbs the client supports. If you design your controllers in a RESTful manner using proper verbs and names there are techniques as the one shown here that allow clients that do not support PUT and DELETE verbs to still invoke those actions.

Darin Dimitrov
But what about ajax requests?
the_drow
What about them? AJAX requests support PUT and DELETE verbs, so you don't need the additional hidden field. They will be automatically dispatched to the proper controller action based on the HTTP verb you are using: `$.ajax({ url: '/products/destroy/123', type: 'DELETE', success: function(result) { alert('product deleted'); } });`
Darin Dimitrov
@Darin Dimitrov: Why ajax requests support PUT and DELETE and normal form requests don't?
the_drow
@the_drow, because in the HTML 4.0 specification the only possible values for the [method attribute](http://www.w3.org/TR/REC-html40/interact/forms.html#adef-method) are GET and POST and I guess browser designers wanted to comply with the specification. As for the XHR object I don't have a clue why it supports PUT and DELETE verbs in addition to GET and POST.
Darin Dimitrov
@Darin Dimitrov: Will it change in HTML 5.0 (EDIT: Yes it will)
the_drow