2012-01-05 80 views
1

是否有可能具有同名GET和POST操作的AsyncController?是否有可能同時具有GET和POST異步控制器操作?

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

是否有可能讓他們共存以任何方式或是否每個異步操作方法必須是唯一的?

+0

請參閱http://stackoverflow.com/questions/4432653/async-get-post-and-action-name-conflicts-in-asp-net-mvc – 2012-01-05 16:31:40

+0

我不確定它有意義嗎[HttpPost ]裝飾*完成的方法。那些不是由控制器內部調用的?如果是這樣,他們不應該有一個POST。 – 2012-01-05 16:34:25

回答

0

你可以有多個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(); 
    } 
} 

(只有在MethodNameAsync方法屬性是通過MVC使用的,因此不需要在MethodNameCompleted方法)

+0

有沒有辦法區分哪個異步方法正在完成,所以我會知道返回視圖A vs視圖B等? – Dismissile 2012-01-05 16:59:45

+0

@Dismissile你可以傳遞viewName作爲參數(例如'AsyncManager.Parameters [「viewName」] =「ViewA」;')或者檢查HttpRequestBase.HttpMethod屬性。 – 2012-01-06 10:12:08

相關問題