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

use*_*165 23 .net c# asp.net-mvc asp.net-web-api asp.net-identity

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

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; }
}
Run Code Online (Sandbox Code Playgroud)

当我注册一个新用户时,我传递了Code自定义属性,RegisterBindingModel但我不知道如何将此自定义属性插入WebUsers表.

我做了如下,但实际上并没有将这个属性与用户名和密码一起插入到表中.

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

而整个功能:

[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();
    }
Run Code Online (Sandbox Code Playgroud)

我错过了什么?我正在寻找类似的问题,但无法找到答案.

Rez*_*aei 58

如果您按照向用户添加自定义字段的所有步骤操作,您将成功完成任务.

以下是向用户添加自定义字段的所有步骤:

  1. 创建ASP.NET Web应用程序
  2. 确保选择MVC并且身份验证单个用户帐户
  3. 转到Models文件夹→打开IdentityModels.csApplicationUser类并添加属性:

    public string Code { get; set; }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 建立项目
  5. 转到工具菜单→ Nuget包管理器 →单击包管理器控制台
  6. 键入Enable-Migrations并按下Enter并等待任务完成.你会看到一个回复​​说:

       Checking if the context targets an existing database...
       Code First Migrations enabled for project WebApplication1.
    
    Run Code Online (Sandbox Code Playgroud)
  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.
    
    Run Code Online (Sandbox Code Playgroud)
  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.
    
    Run Code Online (Sandbox Code Playgroud)

    在此步骤中,如果刷新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" />
    
    Run Code Online (Sandbox Code Playgroud)

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

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

    public string Code { get; set; }
    
    Run Code Online (Sandbox Code Playgroud)
  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>
    
    Run Code Online (Sandbox Code Playgroud)
  11. 转到Controllers文件夹→打开AccountController.cs文件→在http post Register操作中,将创建用户的行更改为:

    var user = new ApplicationUser { UserName = model.Email, Email = model.Email,
        Code= model.Code };
    
    Run Code Online (Sandbox Code Playgroud)
  12. 运行项目并转到/Account/Registerurl并注册新用户.注册用户,如果你去到数据库一次后查看数据dbo.AspNetUsers表,你会看到代码已保存.

下载

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

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

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


小智 6

希望这对其他人有帮助,因为原始帖子已存在1年以上

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

在解决方案资源管理器中,转到“项目”>“模型”>“ IdentityModels.cs”

public class ApplicationUser: IdentityUser(应该是头等舱)。

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; }
}
Run Code Online (Sandbox Code Playgroud)

然后使用NuGet Packagemanager:

  • enable-migrations(如果您还没有的话)
  • 添加迁移[输入]
  • nameYourMigration [输入]
  • (查看迁移文件以确认将要添加您的属性)
  • 更新数据库[输入]
  • 检查您的AspNetUsers db表,以确保正确添加了属性

我希望这有帮助..