當我們使用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)
{
//..
}
}
}
}