添加用户到角色的ASP.NET身份 [英] Add User to Role ASP.NET Identity

查看:113
本文介绍了添加用户到角色的ASP.NET身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道新的成员包括了简单的角色提供者。

I know the new Membership includes a "Simple Role Provider."

我找不到有关创建用户时,创建用户并分配角色的任何帮助。我已经正确添加了创建的 DB 的表的用户。我看 AspNetRoles AspNetUserRoles AspNetUsers 表。

I can't find any help related to creating a user and assigning a role when the user is created. I've added a user which created the tables on the DB correctly. I see the AspNetRoles, AspNetUserRoles, and AspNetUsers tables.

我想在 AspNetUsers 分配从 AspNetRoles A角色给用户其中的 ID < /强>两者的作用/用户都将被存储在AspNetUserRoles

I am wanting to assign a role from AspNetRoles to a user in AspNetUsers which the ID of both the role/user are to be stored in AspNetUserRoles.

我卡在哪里以及如何当我创建用户做到这一点编程的一部分。

I'm stuck on the programming part of where and how to do this when I create the user.

我有一个下拉列表中选择角色,但是使用CF实体与新的ASP.NET识别模型一起我不知道如何采取从下拉列表和用户ID的的SelectedValue的ID和分配角色

I have a dropdown list to select the role, but using the Entity CF along with the new ASP.NET Identity model I'm not sure how to take the ID of the selectedvalue from the dropdown and the UserID and assign the role.

推荐答案

我找到很好的答案在这里<一个href=\"http://stackoverflow.com/questions/19543198/adding-role-dynamically-in-new-vs-2013-identity-usermanager\">Adding动态新VS 2013的UserManager身份角色

I found good answer here Adding Role dynamically in new VS 2013 Identity UserManager

但在情况下提供一个例子,所以你可以检查我要去份额一些默认的code。

But in case to provide an example so you can check it I am gonna share some default code.

首先确保你已经插入的角色。

First make sure you have Roles inserted.

和第二个测试用户的注册方法。

And second test it on user register method.

[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);
        if (result.Succeeded)
        {
            var currentUser = UserManager.FindByName(user.UserName); 

            var roleresult = UserManager.AddToRole(currentUser.Id, "Superusers");

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

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

最后,你必须从角色下拉列表弄好了。

And finally you have to get "Superusers" from the Roles Dropdown List somehow.

这篇关于添加用户到角色的ASP.NET身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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