简体   繁体   English

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

[英]How to extend IdentityUser with custom property

I'm using asp.net Identity 2.0 for users to log into my website, where the authentication details are stored in an SQL database.我正在使用 asp.net Identity 2.0 让用户登录我的网站,其中身份验证详细信息存储在 SQL 数据库中。 Asp.net Identity has been implemented in a standard way as can be found in many online tutorials. Asp.net Identity 已以标准方式实现,可在许多在线教程中找到。

The ApplicationUser class in IdentityModels has been extended to include a custom property: 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; }
}

When I register a new user I pass the Code custom property in the RegisterBindingModel but I'm not sure how to insert this custom property to the WebUsers table.当我注册一个新用户时,我在RegisterBindingModel中传递了Code自定义属性,但我不确定如何将此自定义属性插入到 WebUsers 表中。

I did as bellow but it doesn't actually inserting this property to the table together with the username and password.我做了如下操作,但实际上并没有将此属性与用户名和密码一起插入到表中。

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

And the entire function:以及整个功能:

[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();
    }

What am I missing?我错过了什么? I was looking at similar questions but couldn't find an answer for this.我正在寻找类似的问题,但找不到答案。

If you follow all steps of adding a custom field to user, you will finish the tasks successfully. 如果您按照向用户添加自定义字段的所有步骤操作,您将成功完成任务。

Here is all steps to add a custom field to user: 以下是向用户添加自定义字段的所有步骤:

  1. Create an ASP.NET Web Application 创建ASP.NET Web应用程序
  2. Make sure you select MVC and the Authentication is Individual User Accounts 确保选择MVC并且身份验证单个用户帐户
  3. Go to Models folder → Open IdentityModels.csApplicationUser class and add the property: 转到Models文件夹→打开IdentityModels.csApplicationUser类并添加属性:

     public string Code { get; set; } 
  4. Build the project 建立项目
  5. Go to TOOLS menu → Nuget Package Manager → click Package Manager Console 转到工具菜单→ Nuget包管理器 →单击包管理器控制台
  6. Type Enable-Migrations and press Enter and wait until the task get completed. 键入Enable-Migrations并按Enter键并等待任务完成。 You will see a response which says: 你会看到一个回复​​说:

      Checking if the context targets an existing database... Code First Migrations enabled for project WebApplication1. 
  7. Type Add-Migration "Code" and press Enter and wait until the task get completed. 键入Add-Migration "Code"并按Enter键并等待任务完成。 You will see a response which says: 你会看到一个回复​​说:

     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. Type Update-Database and press Enter and wait until the task get completed. 键入Update-Database并按Enter键并等待任务完成。 You will see a response which says: 你会看到一个回复​​说:

     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. 

    At this step if you refresh SQL Server Object Explorer and go to database and see tables, under dbo.AspNetUsers under columns, you will see the Code field. 在此步骤中,如果刷新SQL Server对象资源管理器并转到数据库并查看表, dbo.AspNetUsers在列下的dbo.AspNetUsers下,您将看到“ Code字段。 If you didn't know which database or even which server you should look for, open Web.Config file and take a look at connection string which is something like this: 如果您不知道应该查找哪个数据库甚至是哪个服务器,请打开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" /> 

    You can see data source (which is sql server instance) and something .mdf which is database name. 您可以看到数据源(这是sql server实例)和.mdf这是数据库名称。

  9. Go to Models folder → Open AccountViewModels.cs file → RegisterViewModel class and add this property: (In APIv2 with EF6, you can add the below line in Models folder → AccountBindingModels file → RegisterBindingModel class) 转到Models文件夹→打开AccountViewModels.cs文件→ RegisterViewModel类并添加此属性:(在APIv2中使用EF6,可以在Models文件夹中添加以下行→AccountBindingModels文件→RegisterBindingModel类)

     public string Code { get; set; } 
  10. Go to Views folder → Account folder → Open Register.cshtml file and add this code near other fields, for example below password: 转到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. Go to Controllers folder → Open AccountController.cs file → in http post Register action, change the line which creates user to this: 转到Controllers文件夹→打开AccountController.cs文件→在http post Register操作中,将创建用户的行更改为:

     var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Code= model.Code }; 
  12. Run project and go to /Account/Register url and register a new user. 运行项目并转到/Account/Register URL并注册新用户。 After registering the user, if you go to database again and View Data of dbo.AspNetUsers table, you will see the code has been saved. 注册用户后,如果再次访问数据库并查看 dbo.AspNetUsers表的数据 ,您将看到代码已保存。

Download 下载

You can clone or download a working example here: 您可以在此处克隆或下载工作示例:

Further reading - How to Add a custom Property to IdentityRole? 进一步阅读 - 如何向IdentityRole添加自定义属性?

If you are interested to know how to add a new property to IdentityRole , take a look at How to Add a custom Property to IdentityRole? 如果您有兴趣知道如何向IdentityRole添加新属性,请查看如何将自定义属性添加到IdentityRole?

Hope this might help others, since the original post is 1+years old 希望这可能对其他人有所帮助,因为原帖是1岁以上

If have already created the project with ' Authentication Individual User Accounts: 如果已使用“ 身份验证个人用户帐户”创建了项目:

In Solution Explorer go to project>Models>IdentityModels.cs 在Solution Explorer中,转到项目>模型> IdentityModels.cs

under public class ApplicationUser: IdentityUser (should be the first class). public class ApplicationUser: IdentityUser (应该是第一个类)。

Add your custom properties after public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) like my example below: 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; }
}

Then using NuGet Packagemanager: 然后使用NuGet Packagemanager:

  • enable-migrations (if you haven't already) enable-migrations(如果你还没有)
  • add-migration [enter] add-migration [enter]
  • nameYourMigration [enter] nameYourMigration [enter]
  • (view the migration file to verify your properties are going to be added) (查看迁移文件以验证是否要添加属性)
  • update-database [enter] update-database [enter]
  • Check your AspNetUsers db table to be sure the properties were added correctly 检查您的AspNetUsers数据库表以确保正确添加属性

I hope this helps.. 我希望这有帮助..

I think the main problem still is you don't register the new claims at the ApplicationUser class. 我认为主要问题仍然是您没有在ApplicationUser类中注册新的声明。

I was having the same problem and I solved it with a few lines after the CreateIdentityAsync . 我遇到了同样的问题,我在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