基于Asp.Net Core编制一个项目,需要给用户添加及删除角色的功能,于是使用到了Identity中的UserManager。

先后解决了几个问题,终于实现了设想。

1. 环境条件

Asp.Net Core 1.0.1

Microsoft.AspNetCore.Identity.EntityFrameworkCore 1.0.0

2. 给用户添加角色(组)使用到UserManager.AddToRolesAsync(),元数据中对AddToRolesAsync的解释为:

        //
// 摘要:
// Add the specified user to the named roles.
//
// 参数:
// user:
// The user to add to the named roles.
//
// roles:
// The name of the roles to add the user to.
//
// 返回结果:
// The System.Threading.Tasks.Task that represents the asynchronous operation, containing
// the Microsoft.AspNetCore.Identity.IdentityResult of the operation.
[AsyncStateMachine(typeof(UserManager<>.<AddToRolesAsync>d__100))]
public virtual Task<IdentityResult> AddToRolesAsync(TUser user, IEnumerable<string> roles);

在我的代码中对应第一个参数的类型是AppcationUser,第二个参数应该是代表角色(组)的字符串列表;

在controller中该行代码为:

await _userManager.AddToRolesAsync(user, selectedRoles)

在默认角色表中有两个关角色名的字段,一个是“Name”,另外一个是“NormalizedName”,如下图所示:

经过尝试,AddToRolesAsync()中的第二个参数应该是“NormalizedName”。如果使用“Name”会出现错误。

3. 删除用户已有角色会使用到UserManager.RemoveFromRoleAsync(),这个方法同样会使用到AddToRolesAsync()中的两个参数,使用方法与AddToRolesAsync()相同。

但是,Identity提供的获取用户现有角色的方法只有:userManager.GetRolesAsync(user),其中参数“user”为<ApplicationUser>。

这个方法的返回值从元数据中给出的解释是:role names。经过测试实际为“Name”字段。

        //
// 摘要:
// Gets a list of role names the specified user belongs to.
//
// 参数:
// user:
// The user whose role names to retrieve.
//
// 返回结果:
// The System.Threading.Tasks.Task that represents the asynchronous operation, containing
// a list of role names.
[AsyncStateMachine(typeof(UserManager<>.<GetRolesAsync>d__105))]
public virtual Task<IList<string>> GetRolesAsync(TUser user);

这样,就出现了不太方便的问题,删除用户角色方法RemoveFromRoleAsync(),需要使用“NormalizedName”,而identity获取的当前用户现有角色只能使用GetRolesAsync(),该方法获得的是角色的“Name”。

所以想当然的代码(如下)不会出现编译错误,同样也不会出现运行错误,但实际运行后,应该被删除的角色实际上删除不了:

var nowRoles = _userManager.GetRolesAsync(user).Result; //得到的nowRoles是角色的Name
await _userManager.RemoveFromRolesAsync(user, nowRoles); //这里需要的是角色的NormalizedName

所以,只能想办法得到当前用户角色的“NormalizedName”,再传递给RemoveFromRoleAsync()。

这面这个办法比较繁琐,但想不到更简单的办法。

var normalizedName = allRoles.Where(r => r.Name == nowRole).First().NormalizedName;

其中:allRoles是这样得到的

var allRoles = _roleManager.Roles;

整个代码是这样的:

                var allRoles = _roleManager.Roles; //系统中所有的角色
var nowRoles = _userManager.GetRolesAsync(user).Result; //该用户现有的角色“Name”
foreach (var nowRole in nowRoles)
{
var normalizedName = allRoles.Where(r => r.Name == nowRole).First().NormalizedName;//取得现有角色的NormalizedName
await _userManager.RemoveFromRoleAsync(user, normalizedName); //删除不要的角色
}
await _userManager.AddToRolesAsync(user, selectedRoles); //添加需要的角色
await _userManager.UpdateAsync(user); //完成储存

上面代码没有进行针对性的添加,代码有些繁杂,不过这样也不会出现错误,省事儿。

至此,结束。

记录,备查。

使用Asp.Net Core Identity给用户添加及删除角色的更多相关文章

  1. asp.net core 系列之用户认证(1)-给项目添加 Identity

    对于没有包含认证(authentication),的项目,你可以使用基架(scaffolder)把 Identity的程序集包加入到项目中,并且选择性的添加Identity的代码进行生成. 虽然基架已 ...

  2. IdentityServer(12)- 使用 ASP.NET Core Identity

    IdentityServer具有非常好的扩展性,其中用户及其数据(包括密码)部分你可以使用任何想要的数据库进行持久化. 如果需要一个新的用户数据库,那么ASP.NET Core Identity是你的 ...

  3. ASP.NET Core Identity Hands On(1)——Identity 初次体验

    ASP.NET Core Identity是用于构建ASP.NET Core Web应用程序的成员资格系统,包括成员资格.登录和用户数据存储 这是来自于 ASP.NET Core Identity 仓 ...

  4. ASP.NET Core Identity Hands On(2)——注册、登录、Claim

    上一篇文章(ASP.NET Core Identity Hands On(1)--Identity 初次体验)中,我们初识了Identity,并且详细分析了AspNetUsers用户存储表,这篇我们将 ...

  5. asp.net core 系列之用户认证(authentication)

    ASP.NET Core 的 identity 是一种需要用户登录的会员系统,用户可以创建一个登录信息存储在 Identity 的的账号, 或者也可以使用第三方登录,支持的第三方登录包括:Facebo ...

  6. IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity

    IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity 原文:http://docs.identityserver.io/en/release ...

  7. IdentityServer4【QuickStart】之使用asp.net core Identity

    使用asp.net core Identity IdentityServer灵活的设计中有一部分是可以将你的用户和他们的数据保存到数据库中的.如果你以一个新的用户数据库开始,那么,asp.net co ...

  8. ASP.NET Core Identity 实战(2)——注册、登录、Claim

    上一篇文章(ASP.NET Core Identity Hands On(1)--Identity 初次体验)中,我们初识了Identity,并且详细分析了AspNetUsers用户存储表,这篇我们将 ...

  9. ASP.NET Core Identity 实战(4)授权过程

    这篇文章我们将一起来学习 Asp.Net Core 中的(注:这样描述不准确,稍后你会明白)授权过程 前情提要 在之前的文章里,我们有提到认证和授权是两个分开的过程,而且认证过程不属于Identity ...

随机推荐

  1. C++之动态数组

    C99支持一种名为变长数组的结构来方便程序员.C++也提供了一种长度可在程序运行时确定的数组类型:动态数组.声明格式为:(声明 int 类型的数组) ; //此处可修改 ArraySize 的值 in ...

  2. .net 事务处理的三种方法

    方法1:直接写入到sql 中 在存储过程中使用 BEGIN TRANS, COMMIT TRANS, ROLLBACK TRANS 实现 begin trans declare@orderDetail ...

  3. Maximo7自定义实现WebService

    最近很多人在群里聊这个话题,我就也一个hello world来实现一下. 1.自定义一个类,继承于AppService 代码如下:

  4. Django(三)

    1.Django请求的生命周期         路由系统 -> 视图函数(获取模板+数据-->渲染) -> 字符串返回给用户   2.路由系统         /index/    ...

  5. install phpexcel using composer in thinkPHP

    Environment Window 10.1 XAMPP 7.0.9 (PHP 7.0.9) thinkPHP 5.0.1 Steps # visit https://getcomposer.org ...

  6. 爱挑剔的acm程序员 acmer

    2015-9-2 acmer敢于承认自己的错误,并积极改进.自信.有些酷爱运动,各个方面都很优秀:有些则认为出去“玩”就不是玩,有自己的小世界,玩电脑才是最爱. 2015-9-1 acmer都很聪明, ...

  7. C#:获取环境信息

    外部环境数据1.需要管理员权限2.需要安装office2003以上完整版3.需要安装flash reader 10.0以上4.需要安装adodb reader;Adobe Acrobat X Pro; ...

  8. UIApplication

    1.UIApplication 是 iPhone 应用程序的开始并且负责初始化并显示 UIWindow,并负责加载应用程序的第一个 UIView 到 UIWindow 窗体中. UIApplicati ...

  9. Thinkphp回顾之(四)查询方法深入学习

    本次讲的查询方法主要有:表达式查询,模糊查询,between语句,in语句,区间查询,统计数据,普通方式查询,但大多数都只是引入数组而已,明白了第一个,其他的也就差不多全明白了,唯一要注意的是在后台中 ...

  10. php读取大文件

    高效率计算文件行数 function count_line($file) { $fp=fopen($file, "r"); $i=0; while(!feof($fp)) { // ...