Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top