Search code examples
asp.net-mvcasynccontroller

Is it possible to have both GET and POST asynchronous controller actions of the same name?


Is it possible to have an AsyncController that has a GET and POST action of the same name?

public class HomeController : AsyncController
{
    [HttpGet]
    public void IndexAsync()
    {
        // ...
    }

    [HttpGet]
    public ActionResult IndexCompleted()
    {
        return View();
    }

    [HttpPost]
    public void IndexAsync(int id)
    {
       // ...
    }

    [HttpPost]
    public ActionResult IndexCompleted(int id)
    {
        return View();
    }
}

When I tried this I got an error:

Lookup for method 'IndexCompleted' on controller type 'HomeController' failed because of an ambiguity between the following methods:
System.Web.Mvc.ActionResult IndexCompleted() on type Web.Controllers.HomeController System.Web.Mvc.ActionResult IndexCompleted(System.Int32) on type Web.Controllers.HomeController

Is it possible to have them co-exist in any way or does every asynchronous action method have to be unique?


Solution

  • You can have the multiple IndexAsync methods, but only the one IndexCompleted method eg:

    public class HomeController : AsyncController
    {
      [HttpGet]
      public void IndexAsync()
      {
        AsyncManager.OutstandingOperations.Increment(1);
        // ...
          AsyncManager.Parameters["id"] = null;
          AsyncManager.OutstandingOperations.Decrement();
        // ...
      }
    
      [HttpPost]
      public void IndexAsync(int id)
      {
        AsyncManager.OutstandingOperations.Increment(1);
       // ...
          AsyncManager.Parameters["id"] = id;
          AsyncManager.OutstandingOperations.Decrement();
        // ...
      }
    
      public ActionResult IndexCompleted(int? id)
      {
        return View();
      }
    }
    

    (Only the attributes on the MethodNameAsync methods are used by MVC, so are not required on the MethodNameCompleted methods)