asp.net-mvc 在 MVC 5 中注册后为用户添加角色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20841262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:24:15  来源:igfitidea点击:

Adding a role for user after registration in MVC 5

asp.net-mvc

提问by SKale

I want to add newly registered user to a generic "User" role in my application. I am using ASP.NET Identity. My code below returns a cryptic error - Exception Details: System.Configuration.Provider.ProviderException: The role '' was not found.

我想将新注册的用户添加到我的应用程序中的通用“用户”角色。我正在使用 ASP.NET 标识。我下面的代码返回一个神秘的错误 - 异常详细信息:System.Configuration.Provider.ProviderException:找不到角色“”。

Do I need to instantiate something in my account controller (role manager etc)? Here my code in the AccountController Register POST action.

我是否需要在我的帐户控制器(角色管理器等)中实例化某些内容?这是我在 AccountController Register POST 操作中的代码。

    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user, model.Password);
            var person = new Person() { 
                UserName = user.UserName, 
                UserId = user.Id, 
                LastName = model.LastName, 
                FirstName = model.FirstName, 
                Email = model.Email, 
                PhoneCell = model.PhoneCell };
                Roles.AddUserToRole(model.UserName, "User");
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                db.People.Add(person);
                db.SaveChanges();
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

回答by Lin

You need to use UserManagerto add role to the user. See below:

您需要使用UserManager向用户添加角色。见下文:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        using (var context = new ApplicationDbContext())
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName };
                var result = await UserManager.CreateAsync(user, model.Password);

                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);

                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);
                userManager.AddToRole(user.Id, "User");

                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }
            // If we got this far, something failed, redisplay form
            return View(model);                
        }
    }

回答by ASPCoder1450

If you're using the built in authentication manager and Account Controller then this wil do it:

如果您使用内置的身份验证管理器和帐户控制器,则可以这样做:

UserManager.AddToRole(user.Id, "<Role>");