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

2023-12-23

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

The ApplicationUser上课于IdentityModels已扩展为包含自定义属性:

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

当我注册新用户时,我通过Code中的自定义属性RegisterBindingModel但我不确定如何将此自定义属性插入到 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 应用程序 https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/getting-started?WT.mc_id=DT-MVP-5003235
  2. 确保您选择MVC验证 is 个人用户帐户
  3. Go to Models文件夹 → 打开IdentityModels.cs应用程序用户类并添加属性:

    public string Code { get; set; }
    
  4. 构建项目
  5. Go to TOOLS menu → Nuget 包管理器→ 点击包管理器控制台
  6. Type Enable-Migrations and press Enter and wait until the task get completed. 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. 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. 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.
    

    到这一步如果刷新SQL Server 对象资源管理器并转到数据库并查看表,在dbo.AspNetUsers在列下,您将看到Code场地。如果您不知道应该查找哪个数据库甚至哪个服务器,请打开网页配置文件并查看连接字符串,如下所示:

    <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. Go to Models文件夹 → 打开AccountViewModels.cs file → 注册视图模型类并添加此属性: (在带有 EF6 的 APIv2 中,您可以在 Models 文件夹 → AccountBindingModels 文件 → RegisterBindingModel 类中添加以下行)

    public string Code { get; set; }
    
  10. Go to Views文件夹 →Account文件夹 → 打开注册.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 控制器文件夹 → 打开AccountController.cs文件 → 在 http 帖子中Register操作,将创建用户的行更改为:

    var user = new ApplicationUser { UserName = model.Email, Email = model.Email,
        Code= model.Code };
    
  12. 运行项目并转到/Account/Registerurl 并注册一个新用户。注册用户后,如果再次访问数据库并查看数据 of dbo.AspNetUsers表中,您将看到代码已保存。

Download

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

  • r-aghaei/AddPropertyToIdentityUserExample https://github.com/r-aghaei/AddPropertyToIdentityUserExample

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

如果您有兴趣了解如何添加新属性IdentityRole, 看一眼如何向 IdentityRole 添加自定义属性? https://stackoverflow.com/a/52029846/3110834

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用自定义属性扩展 IdentityUser 的相关文章

  • 如何从 Visual Studio 将视图导航到其控制器?

    问题是解决方案资源管理器上有 29 个项目 而且项目同时具有 ASP NET MVC 和 ASP NET Web 表单结构 在MVC部分中 Controller文件夹中有大约100个子文件夹 每个文件夹至少有3 4个控制器 视图完全位于不同
  • std::vector 与 std::stack

    有什么区别std vector and std stack 显然 向量可以删除集合中的项目 尽管比列表慢得多 而堆栈被构建为仅后进先出的集合 然而 堆栈对于最终物品操作是否更快 它是链表还是动态重新分配的数组 我找不到关于堆栈的太多信息 但
  • 如何在 C# 中打开 Internet Explorer 属性窗口

    我正在开发一个 Windows 应用程序 我必须向用户提供一种通过打开 IE 设置窗口来更改代理设置的方法 Google Chrome 使用相同的方法 当您尝试更改 Chrome 中的代理设置时 它将打开 Internet Explorer
  • 从经典 ASP 调用 .Net C# DLL 方法

    我正在开发一个经典的 asp 项目 该项目需要将字符串发送到 DLL DLL 会将其序列化并发送到 Zebra 热敏打印机 我已经构建了我的 DLL 并使用它注册了regasm其次是 代码库这使得 IIS 能够识别它 虽然我可以设置我的对象
  • 如何使从 C# 调用的 C(P/invoke)代码“线程安全”

    我有一些简单的 C 代码 它使用单个全局变量 显然这不是线程安全的 所以当我使用 P invoke 从 C 中的多个线程调用它时 事情就搞砸了 如何为每个线程单独导入此函数 或使其线程安全 我尝试声明变量 declspec thread 但
  • 用于 FTP 的文件系统观察器

    我怎样才能实现FileSystemWatcherFTP 位置 在 C 中 这个想法是 每当 FTP 位置添加任何内容时 我都希望将其复制到我的本地计算机 任何想法都会有所帮助 这是我之前问题的后续使用 NET 进行选择性 FTP 下载 ht
  • 方程“a + bx = c + dy”的积分解

    在等式中a bx c dy 所有变量都是整数 a b c and d是已知的 我如何找到整体解决方案x and y 如果我的想法是正确的 将会有无限多个解 由最小公倍数分隔b and d 但我只需要一个解决方案 我可以计算其余的 这是一个例
  • C# 列表通用扩展方法与非通用扩展方法

    这是一个简单的问题 我希望 集合类中有通用和非通用方法 例如List
  • 两个静态变量同名(两个不同的文件),并在任何其他文件中 extern 其中一个

    在一个文件中将变量声明为 static 并在另一个文件中进行 extern 声明 我认为这会在链接时出现错误 因为 extern 变量不会在任何对象中看到 因为在其他文件中声明的变量带有限定符 static 但不知何故 链接器 瑞萨 没有显
  • 结构体的内存大小不同?

    为什么第一种情况不是12 测试环境 最新版本的 gcc 和 clang 64 位 Linux struct desc int parts int nr sizeof desc Output 16 struct desc int parts
  • VB.NET 中的静态方法实现

    我很困惑Static在 VB NET 中的实现 在 C 中 我们可以创建静态类和静态方法来为我们的应用程序编写实用方法 现在 VB NET 让我们创建Module代替静态类 如果我们在模块中创建一个方法 默认情况下它会变成静态的 但在我的应
  • 两个类可以使用 C++ 互相查看吗?

    所以我有一个 A 类 我想在其中调用一些 B 类函数 所以我包括 b h 但是 在 B 类中 我想调用 A 类函数 如果我包含 a h 它最终会陷入无限循环 对吗 我能做什么呢 仅将成员函数声明放在头文件 h 中 并将成员函数定义放在实现文
  • 空指针与 int 等价

    Bjarne 在 C 编程语言 中写道 空指针与整数零不同 但 0 可以用作空指针的指针初始值设定项 这是否意味着 void voidPointer 0 int zero 0 int castPointer reinterpret cast
  • C# 动态/expando 对象的深度/嵌套/递归合并

    我需要在 C 中 合并 2 个动态对象 我在 stackexchange 上找到的所有内容仅涵盖非递归合并 但我正在寻找能够进行递归或深度合并的东西 非常类似于jQuery 的 extend obj1 obj2 http api jquer
  • 复制目录下所有文件

    如何将一个目录中的所有内容复制到另一个目录而不循环遍历每个文件 你不能 两者都不Directory http msdn microsoft com en us library system io directory aspx nor Dir
  • 相当于Linux中的导入库

    在 Windows C 中 当您想要链接 DLL 时 您必须提供导入库 但是在 GNU 构建系统中 当您想要链接 so 文件 相当于 dll 时 您就不需要链接 为什么是这样 是否有等效的 Windows 导入库 注意 我不会谈论在 Win
  • C++ 继承的内存布局

    如果我有两个类 一个类继承另一个类 并且子类仅包含函数 那么这两个类的内存布局是否相同 e g class Base int a b c class Derived public Base only functions 我读过编译器无法对数
  • 当文件流没有新数据时如何防止fgets阻塞

    我有一个popen 执行的函数tail f sometextfile 只要文件流中有数据显然我就可以通过fgets 现在 如果没有新数据来自尾部 fgets 挂起 我试过ferror and feof 无济于事 我怎样才能确定fgets 当
  • C# 使用“?” if else 语句设置值这叫什么

    嘿 我刚刚看到以下声明 return name null name NA 我只是想知道这在 NET 中叫什么 是吗 代表即然后执行此操作 这是一个俗称的 条件运算符 三元运算符 http en wikipedia org wiki Tern
  • 使用 WGL 创建现代 OpenGL 上下文?

    我正在尝试使用 Windows 函数创建 OpenGL 上下文 现代版本 基本上代码就是 创建窗口类 注册班级 创建一个窗口 choose PIXELFORMATDESCRIPTOR并设置它 创建旧版 OpenGL 上下文 使上下文成为当前

随机推荐