標籤:style blog 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);
這裡最基本的角色功能啟用就完成了。
這和原來在網站根目錄下配置Web.config完全不同了。
可選操作:
這個可選操作用於在建立網站的時候,像網站資料庫中添加一個系統管理使用者。如果直接發布給別人用的話 還是挺不錯的,自己用的話可以省略掉。
第一步:在identityconfig.cs可以配置添加一個使用者(使用者名稱為:“[email protected]”,密碼為“[email protected]”)並把該使用者添加到角色("Admin")中。
代碼如下:
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext> { internal void InitializeIdentityForEF() { Models.ApplicationDbContext context = new ApplicationDbContext(); var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); const string name = "[email protected]";//使用者名稱 const string password = "[email protected]";//密碼 const string roleName = "Admin";//使用者要添加到的角色群組 //如果沒有Admin使用者組則建立該組 if (!roleManager.RoleExists(roleName)) { var IdRoleResult = roleManager.Create(new IdentityRole { Name = roleName }); } //如果沒有[email protected]使用者則建立該使用者 var appUser = new ApplicationUser {UserName = name, Email = name }; var IdUserResult = userManager.Create(appUser, password); // 把使用者[email protected]添加到使用者組Admin中 if (!userManager.IsInRole(userManager.FindByEmail(name).Id, roleName)) { IdUserResult = userManager.AddToRole(userManager.FindByEmail(name).Id, roleName); } } }
第二步:修改項目目錄下的Global.asax.cs檔案。
在void Application_Start(object sender, EventArgs e) 類方法中添加如下代碼
// 在第一次啟動網站時初始化資料庫添加管理使用者憑據和admin 角色到資料庫 Database.SetInitializer(new ApplicationDbInitializer()); ApplicationDbInitializer neizhi = new ApplicationDbInitializer(); neizhi.InitializeIdentityForEF();
這兩步再添加的過程中要記得在各自的檔案內添加對用的引用空間。
溫馨提示:
可選操作可以改良下,把第一步獨立出來作為一個類,步驟:你建立個目錄》添加一個“網站初始化”類》添加一個“初始化方法”,把第一步裡的代碼複製進去,儲存。再對應修改Global.asax.cs檔案的最後兩句,也能完成該功能。
個人覺得改良方法比較好。
asp.net identity 2.2.0 在WebForm下的角色啟用和基本使用(一)