簡體   English   中英

如何使用自定義屬性擴展 IdentityUser

[英]How to extend IdentityUser with custom property

我正在使用 asp.net Identity 2.0 讓用戶登錄我的網站,其中身份驗證詳細信息存儲在 SQL 數據庫中。 Asp.net Identity 已以標准方式實現,可在許多在線教程中找到。

IdentityModels中的ApplicationUser類已擴展為包含自定義屬性:

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; }
}

當我注冊一個新用戶時,我在RegisterBindingModel中傳遞了Code自定義屬性,但我不確定如何將此自定義屬性插入到 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();
    }

我錯過了什么? 我正在尋找類似的問題,但找不到答案。

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

以下是向用戶添加自定義字段的所有步驟:

  1. 創建ASP.NET Web應用程序
  2. 確保選擇MVC並且身份驗證單個用戶帳戶
  3. 轉到Models文件夾→打開IdentityModels.csApplicationUser類並添加屬性:

     public string Code { get; set; } 
  4. 建立項目
  5. 轉到工具菜單→ Nuget包管理器 →單擊包管理器控制台
  6. 鍵入Enable-Migrations並按Enter鍵並等待任務完成。 你會看到一個回復​​說:

      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在列下的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 server實例)和.mdf這是數據庫名稱。

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

     public string Code { get; set; } 
  10. 轉到Views文件夾→ 帳戶文件夾→打開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. 轉到Controllers文件夾→打開AccountController.cs文件→在http post Register操作中,將創建用戶的行更改為:

     var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Code= model.Code }; 
  12. 運行項目並轉到/Account/Register URL並注冊新用戶。 注冊用戶后,如果再次訪問數據庫並查看 dbo.AspNetUsers表的數據 ,您將看到代碼已保存。

下載

您可以在此處克隆或下載工作示例:

進一步閱讀 - 如何向IdentityRole添加自定義屬性?

如果您有興趣知道如何向IdentityRole添加新屬性,請查看如何將自定義屬性添加到IdentityRole?

希望這可能對其他人有所幫助,因為原帖是1歲以上

如果已使用“ 身份驗證個人用戶帳戶”創建了項目:

在Solution Explorer中,轉到項目>模型> IdentityModels.cs

public class ApplicationUser: IdentityUser (應該是第一個類)。

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)之后添加自定義屬性public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)如下例所示:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
    **//add custom properties here - these are just examples**
    public bool SendEmails { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

然后使用NuGet Packagemanager:

  • enable-migrations(如果你還沒有)
  • add-migration [enter]
  • nameYourMigration [enter]
  • (查看遷移文件以驗證是否要添加屬性)
  • update-database [enter]
  • 檢查您的AspNetUsers數據庫表以確保正確添加屬性

我希望這有幫助..

我認為主要問題仍然是您沒有在ApplicationUser類中注冊新的聲明。

我遇到了同樣的問題,我在CreateIdentityAsync之后用幾行解決了它。

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
    {
       CookieAuthenticationOptions.AuthenticationType
       var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);

       // Add custom user claims here
        userIdentity.AddClaim(new Claim("Code",this.Code));
       return userIdentity;
    }
    //My extended property
    public string Code { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM