0

In ASP.NET MVC, I have recently found out that:

This doesn't work and results in an HTTP 404.

public class TestController : Controller
{
    [HttpGet]
    [HttpPost]
    public ActionResult Index(TestModel model)
    {
        return View(model);
    }
}

This works fine.

public class TestController : Controller
{
    public ActionResult Index(TestModel model)
    {
        return View(model);
    }
}

This also works fine:

public class TestController : Controller
{
    [HttpGet]
    [ActionName("Index")]
    public ActionResult GetIndex(TestModel model)
    {
        return View("Index", model);
    }

    [HttpPost]
    [ActionName("Index")]
    public ActionResult PostIndex(TestModel model)
    {
        return View("Index", model);
    }
}

I would like an explanation of why the first version doesn't work, but the other two do work. I would also appreciate if someone could tell me how I can modify the first version to make it work. I like the first version because it is more concise (1 method rather than 2) and also filters out unnecessary HTTP methods.

Umar Farooq Khawaja
  • 3,925
  • 1
  • 31
  • 52
  • possible duplicate of [GET and POST to same Controller Action in ASP.NET MVC](http://stackoverflow.com/questions/3232013/get-and-post-to-same-controller-action-in-asp-net-mvc) – Erik Philips Jun 20 '14 at 17:45
  • It does seem to be the same issue, though worded differently. I also asked for the reason why the obvious option doesn't work. – Umar Farooq Khawaja Jun 23 '14 at 09:11

1 Answers1

1

HTTP verb attributes are mutually exclusive, a request cannot be both GET and POST at the same time. Instead, you have to do this:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Index(TestModel model) { ... }
Max Toro
  • 28,282
  • 11
  • 76
  • 114