如何使用自定义属性扩展IdentityUser

我正在使用asp.net Identity 2.0登录我的网站,其中身份validation详细信息存储在SQL数据库中。 Asp.net Identity已经以标准方式实现,可以在许多在线教程中找到。

IdentityModelsApplicationUser类已扩展为包含自定义属性:

 public class ApplicationUser : IdentityUser { public async Task GenerateUserIdentityAsync(UserManager 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 }; 

而整个function:

 [AllowAnonymous] [Route("Register")] public async Task 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并且身份validation单个用户帐户
  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文件并查看连接字符串,如下所示:

      

    您可以看到数据源(这是sql server实例)和.mdf,它是数据库名称。

  9. 转到Models文件夹→打开AccountViewModels.cs文件→ RegisterViewModel类并添加此属性:(在APIv2中使用EF6,可以在Models文件夹中添加以下行→AccountBindingModels文件→RegisterBindingModel类)

     public string Code { get; set; } 
  10. 转到Views文件夹→ 帐户文件夹→打开Register.cshtml文件,并将此代码添加到其他字段附近,例如密码:

     
    @Html.LabelFor(m => m.Code, new { @class = "col-md-2 control-label" })
    @Html.TextBoxFor(m => m.Code, new { @class = "form-control" })
  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表的数据 ,您将看到代码已保存。

下载

您可以在此处克隆或下载一个工作示例:

  • R-aghaei / AddPropertyToIdentityUserExample

进一步阅读 – 如何向IdentityRole添加自定义属性?

如果您有兴趣知道如何向IdentityRole添加新属性,请查看如何将自定义属性添加到IdentityRole?

希望这可能对其他人有所帮助,因为原帖是1岁以上

如果已使用“ 身份validation个人用户帐户”创建了项目:

在Solution Explorer中,转到项目>模型> IdentityModels.cs

public class ApplicationUser: IdentityUser (应该是第一个类)。

public async Task GenerateUserIdentityAsync(UserManager manager)之后添加自定义属性public async Task GenerateUserIdentityAsync(UserManager manager)如下例所示:

 public class ApplicationUser : IdentityUser { public async Task GenerateUserIdentityAsync(UserManager 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]
  • (查看迁移文件以validation是否要添加属性)
  • update-database [enter]
  • 检查您的AspNetUsers数据库表以确保正确添加属性

我希望这有帮助..