在注册页面中,我想要一个下拉列表来添加已在startup.cs中定义的角色,而我无法为asp.net核心找到类似这样的内容。
我尝试过以下方法,它是ASP.NET教程的一部分,但似乎它不适用于CORE。
以下是代码:
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
result = await _userManager.AddToRoleAsync(User.Id, model.RoleName);
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);
// await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation("User created a new account with password.");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
我在第result = await _userManager.AddToRoleAsync(User.Id, model.RoleName);
行收到错误,其中显示'ClaimsPrincipal' does not contain a definition for 'Id' and no extension method 'Id' accepting a first argument of type 'ClaimsPrincipal' could be found (are you missing a using directive or an assembly reference?)
我甚至不知道ClaimsPrincipal是什么。
请帮忙吗?
答案 0 :(得分:1)
这一行:
result = await _userManager.AddToRoleAsync(User.Id, model.RoleName);
应该是:
result = await _userManager.AddToRoleAsync(user.Id, model.RoleName);
请注意使用小写user
变量,而不是控制器属性User
。 User
是已登录用户的声明主体表示,并且没有Id
属性。因此,错误。