How to automatically overload DELETE and PUT if they are not available by the client?

对着背影说爱祢 提交于 2020-01-01 19:12:08

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/3900974/how-to-automatically-overload-delete-and-put-if-they-are-not-available-by-the-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!