在我的以下操作方法中,我在第design time error
行跟踪var result = await _userManager.AddToRoleAsync(user, "AdminRole");
。但是,如果我使用var user = new ApplicationUser { UserName = model.SelectedUserName
来获取用户,则上述行不会给出设计时错误;正如所料,它将run time validation error
视为:User someUSerName already exist
。我理解运行时错误是由于我正在向现有用户添加角色但传递新的实例。 问题:如何将现有用户作为ApplicationUser对象获取,以便将其传递给下面的AddToRoleAsync(....)
?我正在使用ASP.NET Core 1.1.1,个人用户帐户模式,VS2017。
错误:
Cannot convert from Task<MyProj.Model.ApplicationUser> to MyProj.Model.ApplicationUser
控制器
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddUserToRole(RoleRelatedViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = _userManager.FindByNameAsync(model.SelectedUserName); //cannot be used in AddToRoleAsync(user,"AdminRole") since FindByNameAsync returns Task<ApplicationUser>
//var user = new ApplicationUser { UserName = model.SelectedUserName };
var result = await _userManager.AddToRoleAsync(user, "AdminRole");
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
答案 0 :(得分:3)
尝试var user = await _userManager.FindByNameAsync(model.SelectedUserName);
似乎AddToRoleAsync期望ApplicationUser作为第一个参数,但是你给了Task 因此,如果在FindByNameAsync之前使用等待,则调用 user 变量将是ApplicationUser。