【问题标题】:Strongly Typed RedirectToAction (Futures) using async Controllers使用异步控制器的强类型 RedirectToAction (Futures)
【发布时间】:2015-02-04 12:38:37
【问题描述】:

拥有此代码会给我一个警告:Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

    public async Task<ActionResult> Details(Guid id)
    {
        var calendarEvent = await service.FindByIdAsync(id);
        if (calendarEvent == null) return RedirectToAction<CalendarController>(c => c.Index());
        var model = new CalendarEventPresentation(calendarEvent);
        ViewData.Model = model;
        return View();
    }

    public async Task<RedirectResult> Create(CalendarEventBindingModel binding)
    {
        var model = service.Create(binding);
        await context.SaveChangesAsync();
        return this.RedirectToAction<CalendarController>(c => c.Details(model.CalendarEventID));
    }

如果我添加 await 运算符,我会得到:

Error CS4034 The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.

如果我像这样添加async 修饰符:

return this.RedirectToAction<CalendarController>(async c => await c.Details(model.CalendarEventID));

错误是Error CS1989 Async lambda expressions cannot be converted to expression trees

那么如何将强类型 RedirectToAction(我正在使用 MVC Futures)与异步控制器一起使用?

【问题讨论】:

  • 我猜你需要编写一个扩展来接受Func&lt;Task&lt;ViewResult&gt;&gt; 或其他任何东西,然后将其转换为未来版本(非异步)的表达式。
  • mm.. 我不能让它工作:(
  • 由于表达式本身没有被执行,我认为没有问题——除了发出的警告,这真的很烦人。不过,使用#pragma 禁用它们似乎是错误的修复方法。让我们希望有更聪明的人来解决这个问题。以下链接似乎有些相关:stackoverflow.com/questions/24240702/…

标签: c# asynchronous asp.net-mvc-5 asp.net-mvc-futures


【解决方案1】:

我想通了!

我有一个基本控制器,并且我有一个用于异步重定向的扩展方法

protected ActionResult RedirectToAsyncAction<TController>(Expression<Func<TController, Task<ActionResult>>> action)
        where TController : Controller
    {
        Expression<Action<TController>> convertedFuncToAction = Expression.Lambda<Action<TController>>(action.Body, action.Parameters.First());
        return ControllerExtensions.RedirectToAction(this, convertedFuncToAction);
    }

这将防止警告。然后你可以从你的控制器调用 RedirectToAsyncAction。

public ActionResult MyAction()
    {
       // Your code
        return RedirectToAsyncAction<MyController>(c => c.MyAsyncAction(params,..)); // no warnings here
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 2013-09-05
    相关资源
    最近更新 更多