2016-11-10 38 views
6

我正在使用asp.net Identity 2.0進行登錄我的網站,其中身份驗證詳細信息存儲在SQL數據庫中。在許多在線教程中都可以找到Asp.net Identity以標準方式實施。如何使用自定義屬性擴展IdentityUser

ApplicationUserIdentityModels已經擴展到包括自定義屬性:

public class ApplicationUser : IdentityUser 
{ 
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType) 
    { 
     CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); 
     return userIdentity; 
    } 
    //My extended property 
    public string Code { get; set; } 
} 

當我註冊一個用戶,我通過Code自定義屬性在RegisterBindingModel,但我不知道如何插入此定製屬性到WebUsers表。

我做了波紋管,但實際上並沒有將這個屬性與用戶名和密碼一起插入到表中。

var user = new ApplicationUser() { UserName = userName, Email = model.Email, Code=model.Code }; 

和整個功能:

[AllowAnonymous] 
[Route("Register")] 
public async Task<IHttpActionResult> Register(RegisterBindingModel model) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     var userName = !string.IsNullOrEmpty(model.UserName) ? model.UserName : model.Email; 
     //I set it here but it doesn't get inserted to the table. 
     var user = new ApplicationUser() { UserName = userName, Email = model.Email, Code=model.Code }; 

     IdentityResult result = await UserManager.CreateAsync(user, model.Password); 

     if (!result.Succeeded) 
     { 
      return GetErrorResult(result); 
     } 

     return Ok(); 
    } 

我缺少什麼? 我在尋找類似的問題,但無法找到答案。

+0

我認爲你的代碼是好的,你確定代碼屬性被填充到'model'參數中嗎? – jumuro

+0

是的,我確定,我檢查過它。但是,當我檢查數據庫中的表時,新用戶出現,但代碼字段始終爲'null'。 – user3378165

+0

如何定義UserManager?看看https://github.com/tjoudeh/AspNetIdentity.WebApi –

回答

18

如果您按照向用戶添加自定義字段的所有步驟,您將成功完成任務。

這裏是所有步驟將自定義字段添加到用戶:

  1. 創建ASP.NET Web應用程序
  2. 確保你選擇MVC認證個人用戶賬戶
  3. 轉至型號文件夾→打開IdentityModels.csApplicationUser類和屬性添加:

    public string Code { get; set; } 
    
  4. 生成項目
  5. 轉到工具菜單→NuGet包管理器→單擊包管理器控制檯
  6. 類型Enable-Migrations並按輸入並等待任務完成。你會看到它說的響應:

    Checking if the context targets an existing database... 
        Code First Migrations enabled for project WebApplication1. 
    
  7. 類型Add-Migration "Code",然後按Enter鍵等到任務完成得到。你會看到它說的響應:

    Scaffolding migration 'Code'. The Designer Code for this migration 
    file includes a snapshot of your current Code First model. This 
    snapshot is used to calculate the changes to your model when you 
    scaffold the next migration. If you make additional changes to your 
    model that you want to include in this migration, then you can 
    re-scaffold it by running 'Add-Migration Code' again. 
    
  8. 類型Update-Database,然後按Enter鍵等到任務完成得到。你會看到它說的響應:

    Specify the '-Verbose' flag to view the SQL statements being applied 
    to the target database. 
    Applying explicit migrations: [201611132135242_Code]. 
    Applying explicit migration: 201611132135242_Code. 
    Running Seed method. 
    

    在這一步,如果你刷新的SQL Server對象資源管理器並進入數據庫,看看錶,dbo.AspNetUsers下下欄,你會看到Code場。如果你不知道哪個數據庫,甚至你應該找哪個服務器,開放的Web.Config文件,看看連接字符串是這樣的:

    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-WebApplication1-20161114125903.mdf;Initial Catalog=aspnet-WebApplication1-20161114125903;Integrated Security=True" 
    providerName="System.Data.SqlClient" /> 
    

    你可以看到數據源(這是SQL服務器實例)和一些.mdf這是數據庫名稱。

  9. 轉到模型文件夾→打開AccountViewModels.cs文件→RegisterViewModel類,並添加此屬性: (在APIv2與EF6,您可以在模型文件夾→AccountBindingModels文件中添加以下行→RegisterBindingModel類)

    public string Code { get; set; } 
    
  10. 轉到查看文件夾→帳戶文件夾→打開Register.cshtml文件,並添加以下代碼附近其他領域,例如下面的密碼:

    <div class="form-group"> 
        @Html.LabelFor(m => m.Code, new { @class = "col-md-2 control-label" }) 
        <div class="col-md-10"> 
         @Html.TextBoxFor(m => m.Code, new { @class = "form-control" }) 
        </div> 
    </div> 
    
  11. 轉到控制器文件夾→打開AccountController.cs在HTTP POST 註冊行動文件→,改變它創建用戶的行:

    var user = new ApplicationUser { UserName = model.Email, Email = model.Email, 
        Code= model.Code }; 
    
  12. 運行項目,去/Account/Register網址註冊一個新用戶。在註冊用戶之後,如果再次訪問數據庫並且查看數據dbo.AspNetUsers表中,您將看到代碼已保存。

+0

感謝您提供清晰詳細的答案,我唯一缺少的一個步驟是:#9:「進入Models文件夾→打開AccountViewModels .cs'文件→'RegisterViewModel'類,在我的'AccountViewModels。cs'文件沒有'RegisterViewModel'類,我應該添加它嗎?謝謝! – user3378165

+0

不客氣。你將需要它。如果你不需要,View中傳入的模型中不會有'Code'。 –

+0

遵循乾淨的解決方案中的說明,它會清楚你在做什麼。 –

相關問題