6

我已經覆蓋了會員的方法來創建一個自定義的成員。如何在mvc中使用自定義成員身份添加更多自定義字段?

在帳戶模型我已經覆蓋的方法CreateUser

public override MembershipUser CreateUser(string username, string password, 
    string email, string passwordQuestion, string passwordAnswer, 
    bool isApproved, object providerUserKey, out MembershipCreateStatus status) 
{ 
    ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(
     username, password, true); 
    OnValidatingPassword(args); 

    if (args.Cancel) 
    { 
     status = MembershipCreateStatus.InvalidPassword; 
     return null; 
    } 

    if (RequiresUniqueEmail && GetUserNameByEmail(email) != "") 
    { 
     status = MembershipCreateStatus.DuplicateEmail; 
     return null; 
    } 

    MembershipUser u = GetUser(username, false); 
    if (u == null) 
    { 
     UserRepository _user = new UserRepository(); 

     // Here I call my new method which has fields I've created in the 
     // User table; I'm using entity framework.  
     _user.CreateUser(username, password, email); 
     status = MembershipCreateStatus.Success; 
     return GetUser(username, false); 
    } 
    else 
    { 
     status = MembershipCreateStatus.DuplicateUserName; 
    } 

    return null; 
} 

public MembershipUser CreateUser(string username, string password, 
    string email) 
{ 
    using (CustomMembershipDB db = new CustomMembershipDB()) 
    { 
     User user = new User(); 
     user.UserName = username; 
     user.Email = email; 
     user.PasswordSalt = CreateSalt(); 
     user.Password = CreatePasswordHash(password, user.PasswordSalt); 
     user.CreatedDate = DateTime.Now; 
     user.IsActivated = false; 
     user.IsLockedOut = false; 
     user.LastLockedOutDate = DateTime.Now; 
     user.LastLoginDate = DateTime.Now; 

     //Generate an email key 
     // user.NewEmailKey = GenerateKey(); 

     db.AddToUsers(user); 
     db.SaveChanges(); 

     //send mail 
     // SendMail(user); 

     return GetUser(username); 
    } 
} 

現在,這裏我需要添加喜歡的名字和姓氏,但更多的兩個字段我怎麼能傳遞給上述方法? 。

由於覆蓋方法CreateUser會給我一個錯誤,如果我像添加名字和姓氏參數進去:(

+1

你真的不應該嘗試字段添加到類的MembershipUser。如果你想存儲名字,姓氏等,Profile&ProfileProvider('web.config中的'')就是爲此而設計的。 – danludwig 2012-01-06 17:38:30

+0

我該如何使用,請給我任何鏈接? – Neo 2012-01-06 17:42:08

+0

這裏是你的鏈接:https://www.google.com?q=asp.net+profile+provider – danludwig 2012-01-06 17:49:53

回答

1

你可以離開AspNetUsers表完好,並創建一個新表來存儲額外的信息(鏈接到原始一個)。這樣您就不會破壞成員資格提供程序中的任何現有代碼。

原來AspNetUsers表有: [ID],[郵件],[EmailConfirmed],[PasswordHash],[SecurityStamp],[******中國],[PhoneNumberConfirmed],[TwoFactorEnabled],[LockoutEndDateUtc],[LockoutEnabled] [AccessFailedCount],[用戶名]

新表來存儲額外的數據可以有例如: [ID],[用戶ID] [出生日期],[簡歷]等 其中[用戶ID]是國外AspNetUsers表的關鍵。這種方法的

一個優點,就是可以創建多種類型的用戶,每種存儲在不同的表及其相關信息,而普通數據仍處於原始表。

如何:

  1. 先更新RegisterViewModel來包含你需要額外的數據。
  2. 更新在賬戶控制器的註冊方法,這裏的代碼更新插入新的配置文件數據的原始方法:

    [HttpPost] 
    [AllowAnonymous] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Register(RegisterViewModel model) 
    { 
        if (ModelState.IsValid) 
        { 
         var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; 
         IdentityResult result = await UserManager.CreateAsync(user, model.Password); 
         if (result.Succeeded) 
         { 
          // Start of new code ---------------------------------------- 
    
          // Get Id of newly inserted user 
          int userId = user.Id; // Get Id of newly inserted user 
    
          // Create a profile referencing the userId 
          AddUserProfile(userId, model); 
    
          // End of new code ---------------------------------------- 
    
          await SignInAsync(user, isPersistent: false); 
          return RedirectToAction("Index", "Home"); 
         } 
         else 
         { 
          AddErrors(result); 
         } 
        } 
        return View(model); 
    } 
    
  3. 你的願望實現了AddUserProfile(INT用戶id,RegisterViewModel模型)方法。您將從模型對象和userId中收集額外的數據,並將新的配置文件對象保存在數據庫中。
0

從中賺取的MembershipProvider繼承的類並實現由剛調用SqlMembershipProvider的是相同的方法,但改變你想要一個不同的功能等等。

看看這篇文章SQLite 3.0 Membership and Role Provider for ASP.NET 2.0

UPDATE:

ASP.NET中的成員資格系統旨在創建一個標準化的API 與用戶帳戶的工作,任務所面臨的許多Web應用程序 (請參閱本系列文章的第1部分爲更 在深入瞭解會員)。雖然會員制包括 核心用戶相關的屬性 - 等用戶名,密碼,電子郵件地址,並 - 通常情況下更多的信息需要被捕獲 每個用戶。不幸的是,從應用程序到應用程序的這種附加信息可能會大不相同。

與其向會員系統添加其他用戶屬性, Microsoft改爲創建Profile系統來處理其他用戶 屬性。本概要系統允許附加的,用戶特有 性質在Web.config文件中定義,並且負責 堅持這些值的一些數據存儲。

參考:Examining ASP.NET's Membership, Roles, and Profile - Part 6

+0

你可以建議我在哪裏,我可以把我的名字在道具上面的代碼 – Neo 2012-01-06 17:26:21

+0

看看這個帖子HTTP。?: //www.4guysfromrolla.com/articles/101106-1.aspx – 2012-01-06 17:34:01

+0

我做它的MVC你可以跟蹤我的上面的代碼嗎? – Neo 2012-01-06 17:44:59

0

這是怎麼了我已經完成了財產以後這樣的。我添加的事件onCreatedUser到CreateUserWizard控件,當你按下按鈕CreateUser加載方法

protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e) 
    { 
     MembershipUser mu = Membership.GetUser(CreateUserWizard1.UserName); 
     int idOfInsertedUser = (int)mu.ProviderUserKey; 

     TextBox tb1 = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("FirstName"; 
     string firstName= tb1.Text; 
     TextBox tb2 = (TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("LastName"; 
     string lastName= tb2.Text; 

// now you have values of two more fields, and it is time to call your Database methods for inserting them in tables of choice... 
    }