当他与身份注册设置用户的角色的正确方法 [英] Correct way of setting the role for user when he is registered with Identity

查看:288
本文介绍了当他与身份注册设置用户的角色的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我是新来的身份,但我仍想知道什么是时,他正在注册角色分配给用户的正确方法是什么?

I have a question, I'm new to identity, but still i would like to know what would be the correct way of assigning role to a user when he is registering?

我这里有一个code:

I have here a code:

 [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser() { UserName = model.UserName };

            RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
            IdentityRole role = new IdentityRole("Admin");
            await RoleManager.CreateAsync(role);

            // Store Gender as Claim
            user.Claims.Add(new IdentityUserClaim() { ClaimType = ClaimTypes.Gender, ClaimValue = "Male" });
            //user.Roles.Add(new IdentityUserRole() { RoleId=role.Id, UserId=user.Id });
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                //await UserManager.AddToRoleAsync(user.Id, "Admin");

                await SignInAsync(user, isPersistent: false);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                AddErrors(result);
            }
        }

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

这只是测试code,但基本上如果我使用的方法UserManager.AddToROleAsync(...)它的工作原理,但是,在添加用户后,它才会发生,所以基本上我做两次往返数据库

This is just a test code, but basically if i use method UserManager.AddToROleAsync( ...) it works, BUT, it only happens after the user is added, so basically i do twice the roundtrip to database.

我试着用user.Roles.Add(...)这样做,但我在运行时,它得到一个错误。

I tried doing it with user.Roles.Add(...) but i get an error when running it.

所以我的问题是什么做的最有效和最正确的方式?

So my question would be what is the most efficient and correct way of doing it?

推荐答案

我不知道是否有更好的方法。我通常以同样的方式为你做什么,首先创建的角色(如果它不存在),然后创建用户,并作为最后一步,将用户添加到角色。

I don't know if there's a better way. I normally to it the same way as you do, first creating the role (if it doesn't exist), then creating the user, and as a last step adding the user to the role.

要使用user.Roles.Add(...)的作用必须是present。其原因是数据库(在这种情况下实体框架和SQL Server)。当寻找在身份数据库接近,你会看到有间 AspNetRoles AspNetUsers 通过 AspNetUserRoles table表具有的关系的用户ID 的和的角色ID 的一个关键。这意味着用户在用户不存在,但(反之亦然),你不能添加到角色。所以,在我看来,你必须做两次往返(如果你不直接在环境中工作)。

To use user.Roles.Add(...) the role must be present. The reason is the database (in this case Entity Framework and SQL Server). When looking closer at the Identity database you'll see that there is a relationship between the AspNetRoles and AspNetUsers table through the AspNetUserRoles table which has the UserId and the RoleId as a key. That means you can't add a user to a role when the user does not exist yet (and vice versa). So in my opinion you have to do twice the roundtrip (if you don't directly work on the context).

这篇关于当他与身份注册设置用户的角色的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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