【问题标题】:Is it possible to have both GET and POST asynchronous controller actions of the same name?是否可以同时拥有同名的 GET 和 POST 异步控制器操作?
【发布时间】:2012-01-05 16:12:37
【问题描述】:

是否可以有一个具有相同名称的 GET 和 POST 操作的 AsyncController?

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();
    }
}

当我尝试这个时,我得到了一个错误:

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

是否可以让它们以任何方式共存,或者每个异步操作方法都必须是唯一的?

【问题讨论】:

  • 我不确定在 *Completed 方法上使用 [HttpPost] 装饰是否有意义。那些不是由控制器内部调用的吗?如果是这样,他们不应该发帖。

标签: asp.net-mvc asynccontroller


【解决方案1】:

您可以拥有多个IndexAsync 方法,但只能拥有一个IndexCompleted 方法,例如:

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();
  }
}

(MVC只使用MethodNameAsync方法上的属性,所以MethodNameCompleted方法上不需要)

【讨论】:

  • 有没有办法区分正在完成的异步方法,所以我会知道返回视图 A 和视图 B 等?
  • @Dismissile 您可以将 viewName 作为参数传递(例如 AsyncManager.Parameters["viewName"] = "ViewA";),或者检查 HttpRequestBase.HttpMethod 属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多