如何使用ASP.Net MVC中的Task重定向到某个操作
我有一个异步控制器实现如下,
public Task UpdateUser(ProfileModel model) { return Task.Factory.StartNew(showMethod).ContinueWith( t => { return RedirectToAction("ViewUser","UserProfile"); }); }
但是我无法重定向到操作,因为我一直在收到错误,
无法将类型 System.Threading.Taska.Task
隐式转换 为 System.Threading.Taska.Task
但是我真的想重定向到上面提到的Action,我该怎么做呢。
您需要将UpdateUser
操作的返回类型从Task
更改为Task
public Task UpdateUser(ProfileModel model) { return Task.Factory.StartNew(showMethod).ContinueWith( t => { return RedirectToAction("ViewUser","UserProfile"); }); }
或者您可以使用ActionResult
显式设置ContinueWith
方法的generics类型参数,如下所示:
public Task UpdateUser(ProfileModel model) { return Task.Factory.StartNew(showMethod).ContinueWith ( t => { return RedirectToAction("ViewUser","UserProfile"); }); }
对于那些来这里寻找答案的人来说,较新版本的.NET使事情变得更简单。 在方法的定义中使用关键字async
,您可以清理正文。
public async Task UpdateUser(ProfileModel model) { return RedirectToAction("ViewUser","UserProfile"); }
使用此示例 :
public async Task Login(LoginModel model) { //You would do some async work here like I was doing. return RedirectToAction("Action","Controller");//The action must be async as well } public async Task Action() {//This must be an async task return View(); }