如何添加简单的用户角色-ASP.NET MVC C# [英] How to add a simple user roles - ASP.NET MVC C#

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

问题描述

我对ASP.NET MVC还是很陌生,并且我一直在研究添加用户角色的许多不同方法. 为我的ASP.NET MVC网站.我要使用在创建新的ASP.NET MVC项目时自动为您创建的用户数据库.

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. I want to use the users' database(s) that are automatically made for you when you make a new ASP.NET MVC project.

其中包含表格:

  • AspNetRoles
  • AspNetUserClaims
  • AspNetUserLogins
  • AspNetUserRoles
  • AspNetUsers

我一直在看一些教程,我认为这对于初学者来说是个雷区.

I've been looking at a few tutorials and it's a bit of a minefield for beginners I think.

我想要做的就是这样:

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

因此具有角色管理员的用户可以访问索引页面.

So users with the role administrator can access the index page.

推荐答案

第一步是创建admin角色.这很容易:

The first step is to create the admin role. 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 });

这两个步骤都可以而且应该在Migrations\Configuration.csSeed方法中进行处理,以及创建任何初始用户都应该是管理员.

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.

关于管理员向其他用户添加角色的能力,您已经涵盖了第一步:使用[Authorize(Roles = "admin")]保护操作.

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")].

接下来,您将需要一个视图模型来与您的用户一起使用.类似于以下内容:

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

您需要将ApplicationUser映射到该视图模型或从该视图模型映射.然后,您需要在UserViewModel中手动填充两个角色属性:

You'll need to map your ApplicationUser to/from this view model. Then, you'll need to manually populate the two role properties in UserViewModel:

RoleChoices应该是所有可用角色的枚举:

RoleChoices should be an enumerable of all available roles:

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

SelectedRoleIds应该是当前分配给该用户的所有角色的ID的列表:

SelectedRoleIds should be a list of the ids of all roles currently assigned to the user:

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

在编辑现有用户时,必须格外小心,因为如果为同一用户两次保存相同的角色ID,则会出现完整性错误.首先,您需要删除所有已取消选择的角色:

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

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

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