在注册页面中,我想有一个下拉列表来添加已在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是什么。
有什么帮助吗?
这一行:
result = await _userManager.AddToRoleAsync(User.Id, model.RoleName);
应该:
result = await _userManager.AddToRoleAsync(user.Id, model.RoleName);
注意使用小写的user
变量,而不是控制器属性User
。 User
是登录用户的声明主要表示形式,并且没有Id
属性。因此,错误。