您的位置:首页 > 编程语言 > ASP

ASP.NET Identity 角色管理(Roles)

2017-05-02 12:16 351 查看
当我们使用ASP.NET 4.5创建模板项目时,会发现模板只提供了ApplicationUserManager用于用户的登录注册、修改、设置等,而没有提供与用户角色相关的代码,对此就需要我们自己手动的添加。

第一步:在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)
{
//..
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: