简体   繁体   English

如何添加一个简单的用户角色 - ASP.NET MVC C#

[英]How to add a simple user roles - ASP.NET MVC C#

I'm pretty new to ASP.NET MVC, and I've been looking at a lot of different ways of adding User Roles for my ASP.NET MVC site.我是 ASP.NET MVC 的新手,我一直在研究为我的 ASP.NET MVC 站点添加用户角色的许多不同方法。 I want to use the users' database(s) that are automatically made for you when you make a new ASP.NET MVC project.我想使用在您创建新的 ASP.NET MVC 项目时自动为您创建的用户数据库。

That contain the tables:包含表:

  • AspNetRoles AspNet角色
  • AspNetUserClaims AspNet 用户声明
  • AspNetUserLogins AspNet 用户登录
  • AspNetUserRoles AspNet 用户角色
  • AspNetUsers AspNet用户

I've been looking at a few tutorials and it's a bit of a minefield for beginners I think.我一直在看一些教程,我认为这对初学者来说有点雷区。

All I want to be able to do is something like this:我想要做的就是这样:

[Authorize(Roles = "admin")]
public ActionResult Index()
{
    Return View();
}

So users with the role administrator can access the index page.因此具有管理员角色的用户可以访问索引页面。

The first step is to create the admin role.第一步是创建admin角色。 This is easy enough:这很容易:

context.Roles.Add(new IdentityRole { Name = "admin" });
context.SaveChanges();

To add the role to an existing user:要将角色添加到现有用户:

var role = context.Roles.SingleOrDefault(m => m.Name == "admin");
user.Roles.Add(new IdentityUserRole { RoleId = role.Id });

Both of these steps can and should be handled in your Seed method of Migrations\\Configuration.cs , along with creating any initial users that should be administrators.这两个步骤都可以而且应该在您的Migrations\\Configuration.cs Seed方法中处理,同时创建任何应该是管理员的初始用户。

For the ability of administrators to add roles to other users, you've got the first step covered already: protect the action with [Authorize(Roles = "admin")] .对于管理员向其他用户添加角色的能力,您已经完成了第一步:使用[Authorize(Roles = "admin")]保护操作。

Next, you'll need a view model to work with your user.接下来,您需要一个视图模型来与您的用户一起工作。 Something like the following:类似于以下内容:

public class UserViewModel
{
    // User properties you'd like to edit goes here

    public List<int> SelectedRoleIds { get; set; }

    public IEnumerable<SelectListItem> RoleChoices { get; set; }
}

You'll need to map your ApplicationUser to/from this view model.您需要将您的ApplicationUser映射到/从这个视图模型。 Then, you'll need to manually populate the two role properties in UserViewModel :然后,您需要手动填充UserViewModel的两个角色属性:

RoleChoices should be an enumerable of all available roles: RoleChoices应该是所有可用角色的枚举:

model.RoleChoices = context.Roles.Select(m => new SelectListItem
{
    Value = m.Id,
    Text = m.Name
});

SelectedRoleIds should be a list of the ids of all roles currently assigned to the user: SelectedRoleIds应该是当前分配给用户的所有角色的 id 列表:

model.SelectedRoleIds = user.Roles.Select(m => m.RoleId);

In your view, then, you'll construct your multiselect:在您看来,您将构建多选:

@Html.ListBoxFor(m => m.SelectedRoleIds, Model.RoleChoices)

When creating a new user, you can simply set the user's roles directly on post:创建新用户时,您可以直接在帖子上设置用户的角色:

user.Roles = model.SelectedRoleIds.Select(m => new IdentityUserRole { RoleId = m });

When editing an existing user, greater care has to be taken, since you'll get integrity errors if you save the same role id twice for the same user.编辑现有用户时,必须更加小心,因为如果为同一用户保存相同的角色 ID 两次,则会出现完整性错误。 First, you'll need to remove any roles that have been deselected:首先,您需要删除所有已取消选择的角色:

user.Roles.Where(m => !model.SelectedRoleIds.Contains(m.RoleId))
    .ToList().ForEach(role => user.Roles.Remove(role));

Then, you'll need to add any newly selected roles:然后,您需要添加任何新选择的角色:

var existingUserRoles = user.Roles.Select(m => m.RoleId);
model.SelectedRoleIds.Except(existingUserRoles)
    .ToList().ForEach(roleId => user.Roles.Add(new IdentityUserRole
    {
        RoleId = roleId
    }));

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

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