【问题标题】:RedirectToAction to an asynchronous method in ASP.NET MVC [duplicate]RedirectToAction 到 ASP.NET MVC 中的异步方法 [重复]
【发布时间】:2019-06-28 22:05:21
【问题描述】:

我有一个AccountController 和一个带有IndexAsync() 操作的HomeController

如何正确地从AccountControllerAdminUserProfil 操作重定向到HomeControllerIndexAsync 操作?

public async Task<ActionResult> AdminUserProfil(AdminUserViewModel viewModel)
{
    // ...
    if (SomeCondition)
    {
        return this.RedirectToAction<HomeController>(h => h.IndexAsync());
    }
    // ...
}

如果我按原样使用它,我会收到警告:

CS4014 因为没有等待这个调用,所以执行当前 方法在调用完成之前继续。考虑应用 'await' 运算符到调用的结果。

【问题讨论】:

  • 您是否 100% 确定需要执行该操作 async?它的任何其他部分awaiting 有什么特别的吗?
  • @mariocatch 用(部分更新)代码的图像更新了 OP
  • RedirectToAction&lt;T&gt; 方法从何而来?如果您只使用 (h =&gt; h.IndexAsync) 所拥有的(没有调用它的 ()),它是否有效?
  • @KirkLarkin RedirectToAction 是一个 Mvc 控制器扩展 (MvcContrib.dll),如果没有 (),它将无法工作

标签: c# asp.net-mvc async-await


【解决方案1】:

您实际上是在执行示例中的操作。您可以使用类似这样的东西来重定向到操作而不是执行它:

return RedirectToAction(nameof(Controller.ActionName),
                        nameof(Controller).Replace("Controller", ""));

// or hardcode controller name
return RedirectToAction(nameof(Controller.ActionName),
                        "Home");

如果需要返回任务也可以

var result = RedirectToAction(..., ...);
return Task.FromResult(result);

【讨论】:

  • 这取决于你。您可以将变量设置为应返回的内容,然后在底部返回,也可以在知道可以返回后立即返回。
  • 请注意,nameof(Controller) 将返回“HomeController”,但您希望使用字符串“Home”来代替它。
  • 如果我理解得很好,最后return RedirectToAction(nameof(HomeController.IndexAsync), nameof(HomeController)); 应该可以完成这项工作
  • 是的,但正如@JessedeWit 指出的那样,nameof(Controller) 也会将单词Controller 作为字符串的一部分。您可以删除它或对控制器字符串进行硬编码。我会更新答案。
  • 正确,重定向到动作时不涉及等待。​​
猜你喜欢
  • 2017-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-20
相关资源
最近更新 更多