如果客户端不可用,如何自动重载DELETE和PUT? [英] How to automatically overload DELETE and PUT if they are not available by the client?

查看:122
本文介绍了如果客户端不可用,如何自动重载DELETE和PUT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在应用程序启动时检测到客户端不支持 DELETE PUT 动词并自动重载POST动词?

在服务器端,如何将那些重载的POST动词重定向到正确的操作?

说我有一个被覆盖的DELETE请求,如何我应该在控制器中调用与该动作匹配的适当函数吗?

我的猜测是我应该使用一些动作过滤器并使用反射来检查与我的函数匹配的属性(在此示例中: DeleteFoo(Guid ID))。

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

推荐答案

您无法检测到客户端是否支持或不是那些动词。对于不支持html形式的 PUT DELETE 动词的浏览器,您也可以使用 HttpMethodOverride 帮助器,它将在表单中添加一个隐藏字段,指示运行时调用尽管在后台发送了 POST 请求,但仍执行了正确的控制器操作。

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" />
<% } %>

将调用以 [HttpDelete]

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

这里重要的是控制器不应在乎或依赖于什么客户支持的动词。如果您使用适当的动词和名称以RESTful方式设计控制器,那么此处显示的技术就是一种允许不支持 PUT 的客户端的技术。删除动词仍可调用这些动作。

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.

这篇关于如果客户端不可用,如何自动重载DELETE和PUT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆