0

我在 VS.NET 2010 中创建了一个新的 MVC Web 应用程序。我可以毫无问题地访问 localhost/Home/Contact。这是示例应用程序内置的一种方法。

我添加了另一种方法:

[HttpPost]
public ActionResult MyMethod(ClassA content)
{
  return new HttpStatusCodeResult(204);
}

当我尝试使用以下方法访问此方法时:

本地主机/家/我的方法

我收到 404 错误。我已经直接在浏览器 (GET) 中尝试过,也通过 POST 尝试过。知道可能出了什么问题吗?

4

2 回答 2

1

HttpPost属性表示只能通过POST请求访问该操作,它可以保护您免受其他请求类型(GET、PUT 等)的影响。

POSTrequests 也可以在没有该属性的情况下工作,但GETrequests 也可以!这可能会暴露通过 GET 请求插入、更新或删除数据的数据库查询,这是一种不好的做法。想象一下 Google 索引这样的页面:www.mysite.com/Users/Delete/{id}如果您接受GET请求,它可能会删除您的完整用户群。

GET是检索数据,POST是提交数据。有关更多信息,请参阅此问题

有不同的方式来发起POST请求。

您可以在里面包装一个表格Html.BeginForm()

@using (Html.BeginForm())
{
    @Html.LabelFor(m => m.UserName);
    @Html.TextBoxFor(m => m.UserName);

    @Html.LabelFor(m => m.Password);
    @Html.PasswordFor(m => m.UserName);

    <input type="submit" value="Login" />
}

或通过jQuery.post()

$.post(
    '@Url.Action("MyMethod", "Home")',
    {
        // data for ClassA.
        name: $('#username').val(); // example.
    },
    function (result) {
        // handle the result.
    });

但是,如果您使用以下属性修饰您的操作,则此GET请求HttpPost不起作用:

$.get(
    '@Url.Action("MyMethod", "Home")',
    function (result) {
        // this will not work.
    });

或者,如果您尝试通过浏览器访问它。另请参阅此博文

于 2013-10-08T18:01:06.940 回答
0

此方法只能通过 POST 访问。

于 2013-10-08T16:50:17.323 回答