2012-01-05 66 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

相关问题