Asp.net-Mvc
如何自定義簡單的成員資格提供程序以使用我自己的數據庫 ASP.NET mvc 4
這些天我正在探索 ASP.NET MVC 4。如果有人能回答我的問題,我會很高興。
我正在建立一個學術項目“項目管理和支持系統”。我設計了自己的數據庫,我為數據庫中的使用者(兩種使用者:將執行任務的員工和分配/僱用任務的客戶)有自己的表,我打算創建一個新的會員提供者但是我意識到“這是浪費時間——重新發明輪子”。
現在,我正在使用 SimpleMembership 在 ASP.NET MVC4 上建構會員模型(這是 MVC 應用程序會員服務的未來)。它為 ASP.NET 框架提供了更簡潔的會員提供程序,並額外支持 OAuth。
1- 我創建了一個開箱即用的 ASP.NET MVC 4 網際網路應用程序來自定義登錄、註冊和使用者管理邏輯以維護使用者配置文件表。我添加了三個角色:Admin、Employee、Client
通過這篇博文,我可以自定義註冊 http://blog.longle.net/2012/09/25/seding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-自定義使用者屬性/
2-現在,我正在將此表與我自己數據庫中的使用者表同步。考慮到我添加了另一個“帳戶類型”欄位,在註冊期間要求使用者創建特定的配置文件。
非常感謝任何幫助。
乾杯
使用 SimpleMembership 有兩種方法可以儲存和使用該資訊進行身份驗證。
- 您可以使用預設 (UserProfiles) 表,即在“DefaultConnection”字元串指向的數據庫中。
- 您可以使用您的數據庫和其中的表來替換預設的 UserProfiles 表。
選項 1 在其他地方得到了很好的解釋。對於選項 2,請按照以下步驟操作:假設您的數據庫上下文是 mDbContext,而要用於替換 UserProfiles 的表是員工。
- 您的 Employee 模型如下所示
namespace m.Models { public class Employee { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int ID { get; set; } public string UserName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Mobile { get; set; } public Designation Designation { get; set; } .........
- 你的 DbContext 看起來像這樣
namespace m.Models { public class mDBContext : DbContext { DbSet<Employee> Employees { get; set; } ......
- 您需要告訴 WebSecurity 使用您的數據庫。
WebSecurity.InitializeDatabaseConnection("mDBContext", "Employees", "ID", "UserName", autoCreateTables: true);
- 在 AccountModels 的 RegisterModel 類中添加其他欄位
public class RegisterModel { [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Mobile { get; set; } public Designation Designation { get; set; } }
- 在 AccountController Register 方法中為 HttpPost 替換
WebSecurity.CreateUserAndAccount(model.UserName, model.和
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { FirstName = model.FirstName, LastName = model.LastName, Mobile = model.Mobile});
- 如果掛起任何更改(或添加遷移),則重建和更新數據庫。