【问题标题】:MVC Delete not hitting HttpPost MethodMVC 删除未命中 HttpPost 方法
【发布时间】:2014-04-08 06:23:10
【问题描述】:

我正在使用 MVC3。我了解到使用 HttpGet 方法删除项目是一种不好的做法,因为任何人都可以浏览到 url 并删除项目。所以我想对HttpPost Method进行删除操作。

问题是当我点击删除按钮时,它只在 HttpGet 方法上被击中,而不是在 HttpPost 方法上。

我使用过 webgrid 及其 index.cshtml 文件

<div id="DataTable">
@grid.GetHtml(htmlAttributes: new {id="gvMovies" },
columns:grid.Columns(
grid.Column("Title","Movie Title",canSort:true),
grid.Column("Director","Film Maker",canSort:false),   
grid.Column(header:"Action",
format:@<text>
<a href="@Url.Action("Edit", "Movies", new { id = @item.Id })">Edit</a>
@using (Html.BeginForm("Delete", "Movies", new { id = @item.id }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ActionLink("Delete", "Delete", new { id = @item.id }, new { onclick = "return confirm('Are you sure you wish to delete this article?');" })
}

</text>)))
</div>

控制器页面如下

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Delete(int id)
    {
        return RedirectToAction("Index");
    }

【问题讨论】:

    标签: c# asp.net-mvc-3 http-post http-get


    【解决方案1】:

    从概念上讲,使用 POST 动词进行删除是不正确的。 POST - 用于发布信息。正确的方法是从 Delete 方法中删除该属性,然后使用 GET 动词让它消失。

    现在,如果您真的真的需要使用 POST,那么您的第一个错误是您创建了一个链接,而不是一个提交表单的提交按钮。替换

      @Html.ActionLink("Delete", "De...
    

    与:

      <input type="submit" value="Delete">
    

    【讨论】:

    • 如果可能的话,请通过此链接Delete Links Creates Security Holes,您就会知道为什么我讨厌使用 HttpGet 方法执行删除
    • 我能理解您的担忧,但我必须说,提议的解决方案似乎不正确。该帖子的作者所说的是,不仅删除,而且任何更改数据的 Get 操作都容易受到攻击。我宁愿创建安全属性来验证一组可能易受攻击的操作的安全规则。规则可以是:推荐和请求的内容类型。
    【解决方案2】:

    您必须添加提交按钮而不是链接,因此您必须将
    @Html.ActionLink("Delete" 更改为 &lt;input type=submit value="del" &gt;

    如果你想在帖子中发送 id,你可以在表单中添加隐藏的输入,这样你就可以在表单中的提交按钮之前添加一些类似的东西

    <input type="hidden" value=@item.Id name="itemid" >
    

    所以我认为这段代码可以工作

        @using (Html.BeginForm("Delete", "Movies", new { id = @item.id }, FormMethod.Post, new { enctype = "multipart/form-data" }))
    
        {
           <input type="hidden" value=@item.Id name="itemid" >
          <input type=submit value="del" >
        }
    

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多