以下代码让我错误。
_userManager.AddToRoleAsync(_userManager.FindByNameAsync(user.UserName).Id, "Employee");
我已将代码包含在内以供进一步参考。我每次访问网站时都尝试创建一个新用户并添加默认角色。用户已正确添加。此外,我之前已经播种了角色,因此存在角色。
public class ItemsController : Controller
{
private readonly MainContext _context;
private readonly OtherContext _orcontext;
private readonly IHostingEnvironment _appenv;
private readonly UserManager<ApplicationUser> _userManager;
}
public ItemsController(MainContext context, OtherContext _orcontext, IHostingEnvironment appEnvironment, UserManager<ApplicationUser> userManager)
{
_context = context;
_orcontext= orcontext;
_appenv = appEnvironment;
_userManager = userManager;
}
// GET: Items
public async Task<IActionResult> Index()
{
var uname = User.Identity.Name.Remove(0, 5);
if ((await _userManager.FindByNameAsync(uname)) == null)
{
ApplicationUser user = new ApplicationUser
{
UserName = uname
};
IdentityResult result = await _userManager.CreateAsync(user);
_userManager.AddToRoleAsync(_userManager.FindByNameAsync(user.UserName).Id, "Employee");
}
答案 0 :(得分:1)
AddToRoleAsync
的第一个参数是用户实例,而不是id。因此错误。换句话说,删除.Id
位。
_userManager.AddToRoleAsync(_userManager.FindByNameAsync(user.UserName), "Employee");