本文介绍了使用异步控制器的强类型RedirectToAction(未来)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有了此代码,它会给我一个警告: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.

having this code it gives me a warning : 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运算符,则会得到:

if I do add the await operator I get :

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

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

if I add the async modifier like this :

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)?

So how can I use strongly typed RedirectToAction (I'm using MVC Futures) with async controllers?

推荐答案

我已经弄清楚了!

我有一个基本控制器,那里有一个异步重定向的扩展方法

I have a base controller and there I have an extension method for async redirects

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);
    }

这将防止警告.然后,您只需从Controller调用RedirectToAsyncAction.

this will prevent warnings. Then you can just call RedirectToAsyncAction from your Controller.

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

这篇关于使用异步控制器的强类型RedirectToAction(未来)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 08:51