[英]User Registration with roles
我搜索了stackoverflow,但找不到我的问题的确切答案。
我有一个注册页面,我必须使用我已经在 AspNetRoles 中输入的角色注册用户。 每当我运行代码时,我都不明白问题出在哪里,它会给出错误 System.InvalidOperationException: Role xx does not exist。 帐户视图模型
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public string Name { get; set; }
}
帐户控制器
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
//ViewBag.Name = new SelectList(_context.Roles.ToList(), "Name", "Name");
ViewBag.Name = _context.Roles.Select(b => new SelectListItem { Value = b.Name, Text = b.Name });
return View();
}
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var UserPassword = model.Password;
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
Session.Add("UserName", user.Email);
int role = 10;
//Assign Role to user Here. Error is Here
await this.UserManager.AddToRoleAsync(user.Id, model.Name);
//Ends Here
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToAction("Index", "Home", new { user.Email, user.PasswordHash });
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
注册.cshtml
@model ASPNetIdentity.Models.RegisterViewModel
<!--Select the Role Type for the User.-->
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.Name, ViewBag.Name as SelectList, "--Select Role--", new { @class = "form-control" })
</div>
</div>
<!--Ends Here-->
但是错误页面:在此处输入图片描述
需要帮助 问候
我不知道 AddToRoleSync 方法的内容,但在我看来,您应该从 Model.Name 属性中获取角色 id,然后您应该通过 id 值添加角色。
或者您可以创建 select 列表,id 为值,名称为文本。
在我看来,您应该将所需的验证添加到您的选择列表中以强制分配角色。
我希望这个评论对你有用
您传递了错误的参数,如果您阅读了文档,这里说要传递 TUser https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.addtoroleasync?view =aspnetcore-6.0
参数
user TUser 要添加到命名角色的用户。
role String 要将用户添加到的角色的名称。 正确用法是:
var userResult = await this.UserManager.AddToRoleAsync(user, model.Name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.