我无法为用户分配角色。我正在使用.net Core 2.1
我更改了注册方法。注册期间,我为正在创建的用户分配了“管理员”角色。
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var db = new ApplicationDbContext(_optionsBuilder.Options);
var email = db.Users.Where(s => s.Email == Input.Email);
if (email.Count() != 0)
{
ViewData["duplicateEmail"] = "Email is already taken";
return Page();
}
var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { userId = user.Id, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
//#############
if(!await _roleManager.RoleExistsAsync("Admin"))
{
await _userManager.AddToRoleAsync(user, "Admin");
}
//################
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
我仅在标签之间添加了代码。
启动应用程序后,当我单击注册时,我看到
我尝试添加
services.AddIdentity<IdentityUser,IdentityRole>()
.AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>();
到
startup
但是它不起作用。
我怎么做错了?
答案 0 :(得分:1)
您需要在RegisterModel中注入RoleManager<IdentityRole>
,例如:
public class RegisterModel : PageModel
{
private readonly RoleManager<IdentityRole> _roleManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
public RegisterModel(
RoleManager<IdentityRole> roleManager,
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender)
{
_roleManager = roleManager;
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
}
然后尝试将AddRoleManager
添加到您的configureServices中,例如:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();