ASP.NET Identity 角色管理(Roles)
2017-05-02 12:16
351 查看
当我们使用ASP.NET 4.5创建模板项目时,会发现模板只提供了ApplicationUserManager用于用户的登录注册、修改、设置等,而没有提供与用户角色相关的代码,对此就需要我们自己手动的添加。
第一步:在IdentityConfig.cs文件里面添加一个与ApplicationUserManager类似的类:
第二步:在Startup.Auth.cs文件里面创建与ApplicationRoleManager相对应的上下文
第三步:可以在AccountController类里面封装成属性来使用:
第四步:使用RoleManager
第一步:在IdentityConfig.cs文件里面添加一个与ApplicationUserManager类似的类:
//定义角色管理器 public class ApplicationRoleManager : RoleManager<IdentityRole> { public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore) : base(roleStore) { } public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context) { return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>())); } }
第二步:在Startup.Auth.cs文件里面创建与ApplicationRoleManager相对应的上下文
public partial class Startup { //... // 有关配置身份验证的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // 将数据库上下文和用户管理器配置为对每个请求使用单个实例 app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);//添加角色管理器 //... } }
第三步:可以在AccountController类里面封装成属性来使用:
private ApplicationRoleManager _roleManager; public ApplicationRoleManager RoleManager { get { return _roleManager ?? Request.GetOwinContext().Get<ApplicationRoleManager>(); } set { _roleManager = value; } }
第四步:使用RoleManager
public async Task SetRole(string userName, string role) { var oneRole = await RoleManager.FindByNameAsync(role); if (oneRole == null) { var result = await RoleManager.CreateAsync(new IdentityRole(role)); if (!result.Succeeded) { //.. } } var user = await UserManager.FindByNameAsync(userName); if (user != null) { var userRoles = UserManager.GetRoles(user.Id); if (!userRoles.Contains(role)) { var result = await UserManager.AddToRoleAsync(user.Id, role); if (!result.Succeeded) { //.. } } } }
相关文章推荐
- ASP.NET Identity “角色-权限”管理 9
- ASP.NET Identity “角色-权限”管理 2
- ASP.NET Identity “角色-权限”管理 8
- ASP.NET Identity “角色-权限”管理 4
- ASP.NET Identity “角色-权限”管理 6
- ASP.NET Identity “角色-权限”管理 10
- ASP.NET Identity “角色-权限”管理 7
- ASP.NET Identity “角色-权限”管理 目录页
- ASP.NET Identity “角色-权限”管理 5
- ASP.NET Identity “角色-权限”管理 3
- ASP.NET Identity 使用 RoleManager 进行角色管理 (VS2013RC)
- 温故知新ASP.NET 2.0(C#)(6) - Membership&RoleManager(成员资格和角色管理)
- 重新过一遍ASP.NET 2.0(C#)(6) - Membership&RoleManager(成员资格和角色管理)
- 使用ASP.NET Membership 和 角色管理器
- 重新过一遍ASP.NET 2.0(C#)(6) - Membership&RoleManager(成员资格和角色管理)
- ASP.NET 2.0角色及成员管理
- ASP.NET 2.0角色及成员管理
- ASP.NET中用户验证及角色管理
- ASP.NET 2.0角色及成员管理
- asp.net 2.0教程 成员资格和角色管理