简体   繁体   English

带角色的用户注册

[英]User Registration with roles

I have searched over stackoverflow but can't find the exact answer of my question.我搜索了stackoverflow,但找不到我的问题的确切答案。

I have a signup page where I have to register user with a role that I have already entered in AspNetRoles.我有一个注册页面,我必须使用我已经在 AspNetRoles 中输入的角色注册用户。 I don't understand what the problem whenever I run a code, it gives error System.InvalidOperationException: Role xx does not exist.每当我运行代码时,我都不明白问题出在哪里,它会给出错误 System.InvalidOperationException: Role xx does not exist。 AccountViewModel帐户视图模型

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; }
}

AccountController帐户控制器

    // 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);
    }

Register.cshtml注册.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-->                
           

But the error page: enter image description here但是错误页面:在此处输入图片描述

Need help Regards需要帮助 问候

I don't know the content of AddToRoleSync method but in my opinion, You should get the role id from Model.Name property and after that you should add role by id value.我不知道 AddToRoleSync 方法的内容,但在我看来,您应该从 Model.Name 属性中获取角色 id,然后您应该通过 id 值添加角色。

Or you can create select list by id as Value and Name as text.或者您可以创建 select 列表,id 为值,名称为文本。

And in my opinion you should add required validation to your selectlist to assign a role by force.在我看来,您应该将所需的验证添加到您的选择列表中以强制分配角色。

I hope that this comment will be useful to you我希望这个评论对你有用

You are passing the wrong parameters, if you read the docs, here it says to pass TUser https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.addtoroleasync?view=aspnetcore-6.0您传递了错误的参数,如果您阅读了文档,这里说要传递 TUser https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.addtoroleasync?view =aspnetcore-6.0

Parameters参数

user TUser The user to add to the named role. user TUser 要添加到命名角色的用户。

role String The name of the role to add the user to. role String 要将用户添加到的角色的名称。 correct usage is:正确用法是:

var userResult = await this.UserManager.AddToRoleAsync(user, model.Name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM