標籤:style blog http io color ar 使用 sp for
基本環境:asp.net 4.5.2
第一步:在App_Start檔案夾中的IdentityConfig.cs中添加角色控制器。
在namespace xxx內(即最後一個“}”前面)添加 角色控制類
代碼如下:
//配置此應用程式中使用的應用程式角色管理器。RoleManager 在 ASP.NET Identity 中定義,並由此應用程式使用。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
在 public void ConfigureAuth(IAppBuilder app) 方法(約為18行左右)中加入 app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
修改完成後的代碼如下:
app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); //添加的角色管理器 app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
這裡最基本的角色功能啟用就完成了。
可選操作:
這個可選操作用於在建立網站的時候,像網站資料庫中添加一個系統管理使用者。如果直接發布給別人用的話 還是挺不錯的,自己用的話可以省略掉。
第一步:在identityconfig.cs可以配置添加一個使用者(使用者名稱為:“[email protected]”,密碼為“[email protected]”)並把該使用者添加到角色("Admin")中。
代碼如下:
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext> { protected override void Seed(ApplicationDbContext context) { InitializeIdentityForEF(context); base.Seed(context); } //建立使用者名稱為[email protected],密碼為“[email protected]”並把該使用者添加到角色群組"Admin"中 public static void InitializeIdentityForEF(ApplicationDbContext db) { var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>(); const string name = "[email protected]";//使用者名稱 const string password = "[email protected]";//密碼 const string roleName = "Admin";//使用者要添加到的角色群組 //如果沒有Admin使用者組則建立該組 var role = roleManager.FindByName(roleName); if (role == null) { role = new IdentityRole(roleName); var roleresult = roleManager.Create(role); } //如果沒有[email protected]使用者則建立該使用者 var user = userManager.FindByName(name); if (user == null) { user = new ApplicationUser { UserName = name, Email = name }; var result = userManager.Create(user, password); result = userManager.SetLockoutEnabled(user.Id, false); } // 把使用者[email protected]添加到使用者組Admin中 var rolesForUser = userManager.GetRoles(user.Id); if (!rolesForUser.Contains(role.Name)) { var result = userManager.AddToRole(user.Id, role.Name); } } }
第二步:修改Models檔案夾中IdentityModels.cs
在public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 類中添加如下代碼
static ApplicationDbContext() { // 在第一次啟動網站時初始化資料庫添加管理使用者憑據和admin 角色到資料庫
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); }
asp.net identity 2.2.0 中角色啟用和基本使用(一)