The HttpPost
attribute indicates that the action can only be accessed through a POST
request, it protects you from other request types (GET, PUT etc.).
POST
requests will also work without the attribute, but GET
requests will too! This might expose database queries which inserts, updates or removes data through GET requests, which is a bad practice. Imagine Google indexing a page like this: www.mysite.com/Users/Delete/{id}
, if you accept GET
requests, it might delete your complete user-base.
GET
is to retrieve data, and POST
is to submit data. See this question for more info.
There are different ways to initiate a POST
request.
You can wrap a form inside 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" />
}
Or via jQuery.post()
:
$.post(
'@Url.Action("MyMethod", "Home")',
{
// data for ClassA.
name: $('#username').val(); // example.
},
function (result) {
// handle the result.
});
But this GET
request won't work if you decorated your action with the HttpPost
attribute:
$.get(
'@Url.Action("MyMethod", "Home")',
function (result) {
// this will not work.
});
Or if you try to access it through your browser.
Also see this blogpost.