Async GET/POST and action name conflicts in ASP.NE

2019-02-10 15:52发布

The recommended way to make an edit page for ASP.NET MVC is to have two methods on a controller called Edit: one GET action and one POST action, both sharing the same name but overloaded differently. Validation errors are shown on the POST action if the edit fails. Then the user can share or bookmark the URL even if it's off of a POST: the URL goes to the GET version on the return.

So far, so good. But then there's the ASP.NET async pattern on controllers. You have EditAsync and EditCompleted. On the two different EditCompleted methods, how do you tell the GET apart from the POST? If you rename the POST action, you lose the nice behavior discussed earlier.

Is there a nice way to get these two patterns to work together?

1条回答
beautiful°
2楼-- · 2019-02-10 16:14

Generally the XyzAsync() method provides the XyzCompleted() method some state object that tells it what unit of work is being performed, so the XyzCompleted() method can inspect this object and do the right thing. However, if you want to have a different Completed method for each verb, this is possible via the following:

[ActionName("Edit"), HttpGet]
public void EditGetAsync() { }

public ActionResult EditGetCompleted() { }

[ActionName("Edit"), HttpPost]
public void EditPostAsync() { }

public ActionResult EditPostCompleted() { }
查看更多
登录 后发表回答