[英]Return Type from Task<Type> in ASP.NET CORE Controllers
I have a method in my我有一个方法
BaseController基本控制器
public async Task<BaseModel> PopulateBaseModelAsync(BaseModel m)
{
m.CreatedDate = DateTime.Now;
m.CreatedById = await _userManager.GetUserAsync(User);
m.CreatedByUsername = User.Identity.Name;
return m;
}
It's forced to be an async Task
because of the _userManager.GetUserAsync
method.由于
_userManager.GetUserAsync
方法,它被迫成为async Task
。
In a derived controller I want to pass in an BaseModel
and have those three properties populated eg在派生的 controller 中,我想传入一个
BaseModel
并填充这三个属性,例如
DerivedController派生控制器
public async Task<IActionResult> CategoriesCreateAsync(BookingCategory bc)
{
if(bc != null)
{
bc = (BookingCategory)PopulateBaseModelAsync(bc);
_context.BookingCategories.Add(bc);
_context.SaveChanges();
}
return RedirectToAction(nameof(CategoriesIndex));
}
I originally wanted PopulateBaseModel(BaseModel)
to just return a new BaseModel eg below, but because of the forced async
method I'm not sure how to achieve this.我最初希望
PopulateBaseModel(BaseModel)
只返回一个新的 BaseModel 例如下面,但由于强制async
方法,我不知道如何实现这一点。
BaseController基本控制器
public BaseModel PopulateBaseModel(BaseModel m)
{
m.CreatedDate = DateTime.Now;
m.CreatedById = _userManager.GetUser(User); // Must use async :(
m.CreatedByUsername = User.Identity.Name;
return m;
}
DerivedController派生控制器
public IActionResult CategoriesCreate(BookingCategory bc)
{
if(bc != null)
{
bc = (BookingCategory)PopulateBaseModel(bc);
_context.BookingCategories.Add(bc);
_context.SaveChanges();
}
return RedirectToAction(nameof(CategoriesIndex));
}
My main issue is I don't really understand how Task
works - the method我的主要问题是我不太了解
Task
的工作原理 - 方法
public async Task<BaseModel> PopulateBaseModelAsync(BaseModel m)
allows me to return BaseModel
but it won't compile because it can't convert Task<BaseModel> to BookingCategory
允许我返回
BaseModel
但它不会编译,因为它无法convert Task<BaseModel> to BookingCategory
Your just missing an await
:您只是缺少一个
await
:
public async Task<IActionResult> CategoriesCreateAsync(BookingCategory bc)
{
if(bc != null)
{
await PopulateBaseModelAsync(bc);
_context.BookingCategories.Add(bc);
_context.SaveChanges();
}
return RedirectToAction(nameof(CategoriesIndex));
}
Because PopulateBaseModelAsync
returns a Task<IBaseModel>
you need to await it's completion.因为
PopulateBaseModelAsync
返回一个Task<IBaseModel>
你需要等待它的完成。
Here the Task
represents an I/O operation, who's result isn't immediately available.这里的
Task
代表一个 I/O 操作,其结果不是立即可用的。
Without awaiting the Task
, your method would continue before the result is obtained.无需等待
Task
,您的方法将在获得结果之前继续。
No need to re-assign to bc
either, because PopulateBaseModelAsync
is modifying the instance it references.也不需要重新分配给
bc
,因为PopulateBaseModelAsync
正在修改它引用的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.