在MVC 5添加用户角色注册后 [英] Adding a role for user after registration in MVC 5

查看:110
本文介绍了在MVC 5添加用户角色注册后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要新注册的用户添加到我的应用程序的通用用户的角色。我使用ASP.NET身份。下面我的code返回一个神秘的错误 - 异常详细信息:System.Configuration.Provider.ProviderException:角色''没有被发现。

我需要在我的帐户控制器(角色管理器等)来实例化的东西吗?
在这里,我的code中的AccountController注册POST操作。

  // POST:/帐号/注册
    [HttpPost]
    [使用AllowAnonymous]
    [ValidateAntiForgeryToken]
    公共异步任务<&的ActionResult GT;寄存器(RegisterViewModel模型)
    {
        如果(ModelState.IsValid)
        {
            VAR用户=新ApplicationUser(){用户名= model.UserName};
            VAR的结果=等待UserManager.CreateAsync(用户,model.Password);
            变种人=新的Person(){
                用户名= user.UserName,
                用户ID = user.Id,
                姓氏= model.LastName,
                名字= model.FirstName,
                电子邮件= model.Email,
                PhoneCell = model.PhoneCell};
                Roles.AddUserToRole(model.UserName,用户);
            如果(result.Succeeded)
            {
                等待SignInAsync(用户,isPersistent:假);
                db.People.Add(人);
                db.SaveChanges();
                返回RedirectToAction(指数,家);
            }
            其他
            {
                AddErrors(结果);
            }
        }        //如果我们走到这一步,事情失败了,重新显示形式
        返回查看(模型);
    }


解决方案

您需要使用的UserManager 来的角色添加到用户。见下图:

  [HttpPost]
    [使用AllowAnonymous]
    [ValidateAntiForgeryToken]
    公共异步任务<&的ActionResult GT;寄存器(RegisterViewModel模型)
    {
        使用(VAR上下文=新ApplicationDbContext())
        {
            如果(ModelState.IsValid)
            {
                VAR用户=新ApplicationUser(){用户名= model.UserName};
                VAR的结果=等待UserManager.CreateAsync(用户,model.Password);                VAR Rolestore的=新Rolestore的< IdentityRole>(上下文);
                VAR roleManager =新RoleManager< IdentityRole>(Rolestore的);                VAR userStore =新UserStore< ApplicationUser>(上下文);
                VAR的UserManager =新的UserManager< ApplicationUser>(userStore);
                userManager.AddToRole(user.Id,用户);                如果(result.Succeeded)
                {
                    等待SignInAsync(用户,isPersistent:假);
                    返回RedirectToAction(指数,家);
                }
                其他
                {
                    AddErrors(结果);
                }
            }
            //如果我们走到这一步,事情失败了,重新显示形式
            返回查看(模型);
        }
    }

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.

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

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

解决方案

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

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

这篇关于在MVC 5添加用户角色注册后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆