0

I've created a new MVC web app in VS.NET 2010. I can access localhost/Home/Contact without issue. That's a method that comes built into the example app.

I added another method:

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

When I try to access this method using:

localhost/Home/MyMethod

I get a 404 error. I've tried directly in the browser (GET) and also through POSTing. Any idea what might be wrong?

4thSpace
  • 41,122
  • 88
  • 267
  • 450
  • 1
    Can you show us _how_ you post? It's by design that you can't reach the action through a get request, that's why you decorate it with the `HttpPost` attribute. – Henk Mollema Oct 08 '13 at 16:40
  • Try removing `[HttpPost]` and then visit it in your browser. – Nate Oct 08 '13 at 16:51

2 Answers2

1

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.

Community
  • 1
  • 1
Henk Mollema
  • 36,611
  • 11
  • 79
  • 100
0

This method only accessed by POST.

  • Thanks. If someone is doing a POST to that method and I don't have the HttpPost attribute, it should still work right? What is the benefit of using HttpPost - just restriction for POST? – 4thSpace Oct 08 '13 at 17:36
  • Also, I'm returning the 204. I should be able to capture and display that return in the POST'ing page right? That would solve my problem. – 4thSpace Oct 08 '13 at 17:39