首页 文章

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

提问于
浏览
15

我正在使用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();
    }

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

2 回答

  • 41

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

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

    • 创建ASP.NET Web应用程序

    • 确保选择MVC,并且身份验证是单个用户帐户

    • 转到Models文件夹→打开IdentityModels.cs→ApplicationUser类并添加属性:

    public string Code { get; set; }
    
    • 构建项目

    • 转到工具菜单→Nuget包管理器→单击包管理器控制台

    • 键入 Enable-Migrations 并按Enter键并等待任务完成 . 你会看到一个回复说:

    检查上下文是否以现有数据库为目标......
    为项目WebApplication1启用了代码优先迁移 .

    • 键入 Add-Migration "Code" 并按Enter键并等待任务完成 . 你会看到一个回复说:

    脚手架迁移'代码' . 此迁移的Designer代码
    file包含当前Code First模型的快照 . 这个
    快照用于计算模型的更改
    脚手架下一次迁移 . 如果您对其进行了其他更改
    您希望包含在此迁移中的模型,然后您可以
    通过再次运行“添加迁移代码”重新构建它 .

    • 键入 Update-Database 并按Enter键并等待任务完成 . 你会看到一个回复说:

    指定'-Verbose'标志以查看正在应用的SQL语句
    到目标数据库 .
    应用显式迁移:[201611132135242_Code] .
    应用显式迁移:201611132135242_Code .
    运行种子方法 .

    在此步骤中,如果刷新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 server实例)和.mdf这是数据库名称 .

    • 转到Models文件夹→打开AccountViewModels.cs文件→RegisterViewModel类并添加此属性:(在APIv2中使用EF6,可以在Models文件夹中添加以下行→AccountBindingModels文件→RegisterBindingModel类)
    public string Code { get; set; }
    
    • 转到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>
    
    • 转到Controllers文件夹→打开AccountController.cs文件→在http post Register操作中,将创建用户的行更改为:
    var user = new ApplicationUser { UserName = model.Email, Email = model.Email,
        Code= model.Code };
    
    • 运行项目并转到 /Account/Register url并注册新用户 . 注册用户后,如果再次访问数据库并查看dbo.AspNetUsers表的数据,您将看到代码已保存 .

    Download

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

    Further reading - How to Add a custom Property to IdentityRole?

    如果您有兴趣知道如何向 IdentityRole 添加新属性,请查看How to Add a custom Property to IdentityRole?

  • 3

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

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

    在Solution Explorer中,转到项目>模型> 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; }
    }
    

    然后使用NuGet Packagemanager:

    • enable-migrations(如果还没有)

    • add-migration [enter]

    • nameYourMigration [enter]

    • (查看迁移文件以验证是否要添加属性)

    • update-database [enter]

    • 检查您的AspNetUsers数据库表以确保正确添加了属性


    我希望这有帮助..

相关问题