gpt4 book ai didi

c# - 使用异步 Controller 的强类型 RedirectToAction( future )

转载 作者:太空狗 更新时间:2023-10-29 20:39:15 24 4
gpt4 key购买 nike

有了这段代码,它会给我一个警告:因为没有等待这个调用,所以在调用完成之前继续执行当前方法。考虑将“等待”运算符应用于调用结果。

    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 运算符,我会得到:

错误 CS4034 'await' 运算符只能在异步 lambda 表达式中使用。考虑使用“async”修饰符标记此 lambda 表达式。

如果我像这样添加 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)与异步 Controller 一起使用?

最佳答案

我想通了!

我有一个基本 Controller ,那里有一个用于异步重定向的扩展方法

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。

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

关于c# - 使用异步 Controller 的强类型 RedirectToAction( future ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28321638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com