添加、 下载和删除标识到 ASP.NET Core 项目中的自定义用户数据Add, download, and delete custom user data to Identity in an ASP.NET Core project

本文内容

作者:Rick Anderson

本文介绍以下操作:

  • 将自定义用户数据添加到 ASP.NET Core web 应用程序。
  • 使用 PersonalDataAttribute 特性标记自定义用户数据模型,使其自动可供下载和删除。使数据能够下载和删除有助于满足GDPR要求。

项目示例将创建从 Razor 页 web 应用,但了 ASP.NET Core MVC web 应用的类似的说明。

查看或下载示例代码如何下载

必备条件Prerequisites

.NET Core 3.0 SDK 或更高版本

.NET Core 2.2 SDK 或更高版本

创建 Razor Web 应用Create a Razor web app

  • 从 Visual Studio“文件”菜单中选择“新建” “项目” > 。将项目命名为 " WebApp1 " (如果你希望它与下载示例代码的命名空间相匹配)。
  • 选择ASP.NET Core Web 应用程序>确定
  • 在下拉列表中选择ASP.NET Core 3.0
  • 选择Web 应用程序>确定
  • 生成并运行该项目。
  • 从 Visual Studio“文件”菜单中选择“新建” “项目” > 。将项目命名为 " WebApp1 " (如果你希望它与下载示例代码的命名空间相匹配)。
  • 选择ASP.NET Core Web 应用程序>确定
  • 在下拉列表中选择ASP.NET Core 2.2
  • 选择Web 应用程序>确定
  • 生成并运行该项目。
  1. dotnet new webapp -o WebApp1

运行标识基架Run the Identity scaffolder

  • 解决方案资源管理器中,右键单击项目 >添加 > 新的基架项
  • 在 "添加基架" 对话框的左窗格中,选择 "标识" > "添加"。
  • 在 "添加标识" 对话框中,选择以下选项:
    • 选择现有的布局文件 ~/Pages/Shared/_Layout cshtml
    • 选择要重写的以下文件:
      • 帐户/注册
      • 帐户/管理/索引
    • 选择 " + " 按钮以创建新的数据上下文类。如果项目命名为WebApp1,则接受类型(WebApp1. WebApp1Context。
    • 选择 " + " 按钮以创建新的用户类。接受类型(如果项目命名为 " WebApp1",则为WebApp1User ) > "添加"。
  • 选择 添加

如果以前未安装 ASP.NET Core 基架,请立即进行安装:

  1. dotnet tool install -g dotnet-aspnet-codegenerator

将对VisualStudio的包引用添加到项目(.csproj)文件中。在项目目录中运行以下命令:

  1. dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
  2. dotnet restore

运行以下命令以列出标识基架选项:

  1. dotnet aspnet-codegenerator identity -h

在项目文件夹中,运行标识基架:

  1. dotnet aspnet-codegenerator identity -u WebApp1User -fi Account.Register;Account.Manage.Index

按照 "迁移"、"UseAuthentication" 和 "布局" 中的说明执行以下步骤:

  • 创建迁移并更新数据库。
  • 已将 UseAuthentication 添加到 Startup.Configure
  • <partial name="_LoginPartial" /> 添加到布局文件中。
  • 测试应用:
    • 注册用户
    • 选择新用户名("注销" 链接旁边)。您可能需要展开窗口或选择要显示的用户名称和其他链接的导航栏图标。
    • 选择 "个人数据" 选项卡。
    • 选择 "下载" 按钮,然后检查PersonalData文件。
    • 测试删除按钮,该按钮将删除已登录的用户。

向标识数据库中添加自定义用户数据Add custom user data to the Identity DB

用自定义属性更新 IdentityUser 派生类。如果已将项目命名为 WebApp1,则该文件的名称为Areas/Identity/Data/WebApp1User使用以下代码更新文件:

  1. using System;
  2. using Microsoft.AspNetCore.Identity;
  3. namespace WebApp1.Areas.Identity.Data
  4. {
  5. public class WebApp1User : IdentityUser
  6. {
  7. [PersonalData]
  8. public string Name { get; set; }
  9. [PersonalData]
  10. public DateTime DOB { get; set; }
  11. }
  12. }
  1. using Microsoft.AspNetCore.Identity;
  2. using System;
  3. namespace WebApp1.Areas.Identity.Data
  4. {
  5. public class WebApp1User : IdentityUser
  6. {
  7. [PersonalData]
  8. public string Name { get; set; }
  9. [PersonalData]
  10. public DateTime DOB { get; set; }
  11. }
  12. }

具有PersonalData属性的属性为:

  • 当 "区域/标识/页面/帐户/管理/DeletePersonalData " Razor 页面调用 UserManager.Delete时删除。
  • 区域/标识/页面/帐户/管理/DownloadPersonalData Razor 页面包含在下载的数据中。

更新 Account/Manage/Index.cshtml 页Update the Account/Manage/Index.cshtml page

用以下突出显示的代码更新区域/标识/页/帐户/管理/ InputModel 中的:

  1. public partial class IndexModel : PageModel
  2. {
  3. private readonly UserManager<WebApp1User> _userManager;
  4. private readonly SignInManager<WebApp1User> _signInManager;
  5. public IndexModel(
  6. UserManager<WebApp1User> userManager,
  7. SignInManager<WebApp1User> signInManager)
  8. {
  9. _userManager = userManager;
  10. _signInManager = signInManager;
  11. }
  12. public string Username { get; set; }
  13. [TempData]
  14. public string StatusMessage { get; set; }
  15. [BindProperty]
  16. public InputModel Input { get; set; }
  17. public class InputModel
  18. {
  19. [Required]
  20. [DataType(DataType.Text)]
  21. [Display(Name = "Full name")]
  22. public string Name { get; set; }
  23. [Required]
  24. [Display(Name = "Birth Date")]
  25. [DataType(DataType.Date)]
  26. public DateTime DOB { get; set; }
  27. [Phone]
  28. [Display(Name = "Phone number")]
  29. public string PhoneNumber { get; set; }
  30. }
  31. private async Task LoadAsync(WebApp1User user)
  32. {
  33. var userName = await _userManager.GetUserNameAsync(user);
  34. var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
  35. Username = userName;
  36. Input = new InputModel
  37. {
  38. Name = user.Name,
  39. DOB = user.DOB,
  40. PhoneNumber = phoneNumber
  41. };
  42. }
  43. public async Task<IActionResult> OnGetAsync()
  44. {
  45. var user = await _userManager.GetUserAsync(User);
  46. if (user == null)
  47. {
  48. return NotFound(
  49. $"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  50. }
  51. await LoadAsync(user);
  52. return Page();
  53. }
  54. public async Task<IActionResult> OnPostAsync()
  55. {
  56. var user = await _userManager.GetUserAsync(User);
  57. if (user == null)
  58. {
  59. return NotFound(
  60. $"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  61. }
  62. if (!ModelState.IsValid)
  63. {
  64. await LoadAsync(user);
  65. return Page();
  66. }
  67. var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
  68. if (Input.PhoneNumber != phoneNumber)
  69. {
  70. var setPhoneResult = await _userManager.SetPhoneNumberAsync(user,
  71. Input.PhoneNumber);
  72. if (!setPhoneResult.Succeeded)
  73. {
  74. var userId = await _userManager.GetUserIdAsync(user);
  75. throw new InvalidOperationException(
  76. $"Unexpected error occurred setting phone number for user with ID '{userId}'.");
  77. }
  78. }
  79. if (Input.Name != user.Name)
  80. {
  81. user.Name = Input.Name;
  82. }
  83. if (Input.DOB != user.DOB)
  84. {
  85. user.DOB = Input.DOB;
  86. }
  87. await _userManager.UpdateAsync(user);
  88. await _signInManager.RefreshSignInAsync(user);
  89. StatusMessage = "Your profile has been updated";
  90. return RedirectToPage();
  91. }
  92. }

用以下突出显示的标记更新区域/标识/页/帐户/管理/索引。 cshtml

  1. @page
  2. @model IndexModel
  3. @{
  4. ViewData["Title"] = "Profile";
  5. ViewData["ActivePage"] = ManageNavPages.Index;
  6. }
  7. <h4>@ViewData["Title"]</h4>
  8. <partial name="_StatusMessage" model="Model.StatusMessage" />
  9. <div class="row">
  10. <div class="col-md-6">
  11. <form id="profile-form" method="post">
  12. <div asp-validation-summary="All" class="text-danger"></div>
  13. <div class="form-group">
  14. <label asp-for="Username"></label>
  15. <input asp-for="Username" class="form-control" disabled />
  16. </div>
  17. <div class="form-group">
  18. <label asp-for="Input.Name"></label>
  19. <input asp-for="Input.Name" class="form-control" />
  20. </div>
  21. <div class="form-group">
  22. <label asp-for="Input.DOB"></label>
  23. <input asp-for="Input.DOB" class="form-control" />
  24. </div>
  25. <div class="form-group">
  26. <label asp-for="Input.PhoneNumber"></label>
  27. <input asp-for="Input.PhoneNumber" class="form-control" />
  28. <span asp-validation-for="Input.PhoneNumber"
  29. class="text-danger"></span>
  30. </div>
  31. <button id="update-profile-button" type="submit"
  32. class="btn btn-primary">Save</button>
  33. </form>
  34. </div>
  35. </div>
  36. @section Scripts {
  37. <partial name="_ValidationScriptsPartial" />
  38. }
  1. public partial class IndexModel : PageModel
  2. {
  3. private readonly UserManager<WebApp1User> _userManager;
  4. private readonly SignInManager<WebApp1User> _signInManager;
  5. private readonly IEmailSender _emailSender;
  6. public IndexModel(
  7. UserManager<WebApp1User> userManager,
  8. SignInManager<WebApp1User> signInManager,
  9. IEmailSender emailSender)
  10. {
  11. _userManager = userManager;
  12. _signInManager = signInManager;
  13. _emailSender = emailSender;
  14. }
  15. public string Username { get; set; }
  16. public bool IsEmailConfirmed { get; set; }
  17. [TempData]
  18. public string StatusMessage { get; set; }
  19. [BindProperty]
  20. public InputModel Input { get; set; }
  21. public class InputModel
  22. {
  23. [Required]
  24. [DataType(DataType.Text)]
  25. [Display(Name = "Full name")]
  26. public string Name { get; set; }
  27. [Required]
  28. [Display(Name = "Birth Date")]
  29. [DataType(DataType.Date)]
  30. public DateTime DOB { get; set; }
  31. [Required]
  32. [EmailAddress]
  33. public string Email { get; set; }
  34. [Phone]
  35. [Display(Name = "Phone number")]
  36. public string PhoneNumber { get; set; }
  37. }
  38. public async Task<IActionResult> OnGetAsync()
  39. {
  40. var user = await _userManager.GetUserAsync(User);
  41. if (user == null)
  42. {
  43. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  44. }
  45. var userName = await _userManager.GetUserNameAsync(user);
  46. var email = await _userManager.GetEmailAsync(user);
  47. var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
  48. Username = userName;
  49. Input = new InputModel
  50. {
  51. Name = user.Name,
  52. DOB = user.DOB,
  53. Email = email,
  54. PhoneNumber = phoneNumber
  55. };
  56. IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
  57. return Page();
  58. }
  59. public async Task<IActionResult> OnPostAsync()
  60. {
  61. if (!ModelState.IsValid)
  62. {
  63. return Page();
  64. }
  65. var user = await _userManager.GetUserAsync(User);
  66. if (user == null)
  67. {
  68. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  69. }
  70. var email = await _userManager.GetEmailAsync(user);
  71. if (Input.Email != email)
  72. {
  73. var setEmailResult = await _userManager.SetEmailAsync(user, Input.Email);
  74. if (!setEmailResult.Succeeded)
  75. {
  76. var userId = await _userManager.GetUserIdAsync(user);
  77. throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{userId}'.");
  78. }
  79. }
  80. if (Input.Name != user.Name)
  81. {
  82. user.Name = Input.Name;
  83. }
  84. if (Input.DOB != user.DOB)
  85. {
  86. user.DOB = Input.DOB;
  87. }
  88. var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
  89. if (Input.PhoneNumber != phoneNumber)
  90. {
  91. var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
  92. if (!setPhoneResult.Succeeded)
  93. {
  94. var userId = await _userManager.GetUserIdAsync(user);
  95. throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
  96. }
  97. }
  98. await _userManager.UpdateAsync(user);
  99. await _signInManager.RefreshSignInAsync(user);
  100. StatusMessage = "Your profile has been updated";
  101. return RedirectToPage();
  102. }
  103. public async Task<IActionResult> OnPostSendVerificationEmailAsync()
  104. {
  105. if (!ModelState.IsValid)
  106. {
  107. return Page();
  108. }
  109. var user = await _userManager.GetUserAsync(User);
  110. if (user == null)
  111. {
  112. return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
  113. }
  114. var userId = await _userManager.GetUserIdAsync(user);
  115. var email = await _userManager.GetEmailAsync(user);
  116. var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  117. var callbackUrl = Url.Page(
  118. "/Account/ConfirmEmail",
  119. pageHandler: null,
  120. values: new { userId = userId, code = code },
  121. protocol: Request.Scheme);
  122. await _emailSender.SendEmailAsync(
  123. email,
  124. "Confirm your email",
  125. $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
  126. StatusMessage = "Verification email sent. Please check your email.";
  127. return RedirectToPage();
  128. }
  129. }

用以下突出显示的标记更新区域/标识/页/帐户/管理/索引。 cshtml

  1. @page
  2. @model IndexModel
  3. @{
  4. ViewData["Title"] = "Profile";
  5. ViewData["ActivePage"] = ManageNavPages.Index;
  6. }
  7. <h4>@ViewData["Title"]</h4>
  8. <partial name="_StatusMessage" for="StatusMessage" />
  9. <div class="row">
  10. <div class="col-md-6">
  11. <form id="profile-form" method="post">
  12. <div asp-validation-summary="All" class="text-danger"></div>
  13. <div class="form-group">
  14. <label asp-for="Username"></label>
  15. <input asp-for="Username" class="form-control" disabled />
  16. </div>
  17. <div class="form-group">
  18. <label asp-for="Input.Email"></label>
  19. @if (Model.IsEmailConfirmed)
  20. {
  21. <div class="input-group">
  22. <input asp-for="Input.Email" class="form-control" />
  23. <span class="input-group-addon" aria-hidden="true"><span class="glyphicon glyphicon-ok text-success"></span></span>
  24. </div>
  25. }
  26. else
  27. {
  28. <input asp-for="Input.Email" class="form-control" />
  29. <button id="email-verification" type="submit" asp-page-handler="SendVerificationEmail" class="btn btn-link">Send verification email</button>
  30. }
  31. <span asp-validation-for="Input.Email" class="text-danger"></span>
  32. </div>
  33. <div class="form-group">
  34. <label asp-for="Input.Name"></label>
  35. <input asp-for="Input.Name" class="form-control" />
  36. </div>
  37. <div class="form-group">
  38. <label asp-for="Input.DOB"></label>
  39. <input asp-for="Input.DOB" class="form-control" />
  40. </div>
  41. <div class="form-group">
  42. <label asp-for="Input.PhoneNumber"></label>
  43. <input asp-for="Input.PhoneNumber" class="form-control" />
  44. <span asp-validation-for="Input.PhoneNumber" class="text-danger"></span>
  45. </div>
  46. <button id="update-profile-button" type="submit" class="btn btn-primary">Save</button>
  47. </form>
  48. </div>
  49. </div>
  50. @section Scripts {
  51. <partial name="_ValidationScriptsPartial" />
  52. }

更新 account/Register.cshtml 页面Update the Account/Register.cshtml page

用以下突出显示的代码更新区域/标识/页/帐户/注册. .cs中的 InputModel

  1. [AllowAnonymous]
  2. public class RegisterModel : PageModel
  3. {
  4. private readonly SignInManager<WebApp1User> _signInManager;
  5. private readonly UserManager<WebApp1User> _userManager;
  6. private readonly ILogger<RegisterModel> _logger;
  7. private readonly IEmailSender _emailSender;
  8. public RegisterModel(
  9. UserManager<WebApp1User> userManager,
  10. SignInManager<WebApp1User> signInManager,
  11. ILogger<RegisterModel> logger,
  12. IEmailSender emailSender)
  13. {
  14. _userManager = userManager;
  15. _signInManager = signInManager;
  16. _logger = logger;
  17. _emailSender = emailSender;
  18. }
  19. [BindProperty]
  20. public InputModel Input { get; set; }
  21. public string ReturnUrl { get; set; }
  22. public IList<AuthenticationScheme> ExternalLogins { get; set; }
  23. public class InputModel
  24. {
  25. [Required]
  26. [DataType(DataType.Text)]
  27. [Display(Name = "Full name")]
  28. public string Name { get; set; }
  29. [Required]
  30. [Display(Name = "Birth Date")]
  31. [DataType(DataType.Date)]
  32. public DateTime DOB { get; set; }
  33. [Required]
  34. [EmailAddress]
  35. [Display(Name = "Email")]
  36. public string Email { get; set; }
  37. [Required]
  38. [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
  39. [DataType(DataType.Password)]
  40. [Display(Name = "Password")]
  41. public string Password { get; set; }
  42. [DataType(DataType.Password)]
  43. [Display(Name = "Confirm password")]
  44. [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
  45. public string ConfirmPassword { get; set; }
  46. }
  47. public async Task OnGetAsync(string returnUrl = null)
  48. {
  49. ReturnUrl = returnUrl;
  50. ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
  51. }
  52. public async Task<IActionResult> OnPostAsync(string returnUrl = null)
  53. {
  54. returnUrl = returnUrl ?? Url.Content("~/");
  55. ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
  56. if (ModelState.IsValid)
  57. {
  58. var user = new WebApp1User {
  59. Name = Input.Name,
  60. DOB = Input.DOB,
  61. UserName = Input.Email,
  62. Email = Input.Email
  63. };
  64. var result = await _userManager.CreateAsync(user, Input.Password);
  65. if (result.Succeeded)
  66. {
  67. _logger.LogInformation("User created a new account with password.");
  68. var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  69. code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
  70. var callbackUrl = Url.Page(
  71. "/Account/ConfirmEmail",
  72. pageHandler: null,
  73. values: new { area = "Identity", userId = user.Id, code = code },
  74. protocol: Request.Scheme);
  75. await _emailSender.SendEmailAsync(Input.Email,
  76. "Confirm your email",
  77. $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
  78. if (_userManager.Options.SignIn.RequireConfirmedAccount)
  79. {
  80. return RedirectToPage("RegisterConfirmation", new { email = Input.Email });
  81. }
  82. else
  83. {
  84. await _signInManager.SignInAsync(user, isPersistent: false);
  85. return LocalRedirect(returnUrl);
  86. }
  87. }
  88. foreach (var error in result.Errors)
  89. {
  90. ModelState.AddModelError(string.Empty, error.Description);
  91. }
  92. }
  93. // If we got this far, something failed, redisplay form
  94. return Page();
  95. }
  96. }

用以下突出显示的标记更新区域/标识/页/帐户/注册. cshtml

  1. @page
  2. @model RegisterModel
  3. @{
  4. ViewData["Title"] = "Register";
  5. }
  6. <h1>@ViewData["Title"]</h1>
  7. <div class="row">
  8. <div class="col-md-4">
  9. <form asp-route-returnUrl="@Model.ReturnUrl" method="post">
  10. <h4>Create a new account.</h4>
  11. <hr />
  12. <div asp-validation-summary="All" class="text-danger"></div>
  13. <div class="form-group">
  14. <label asp-for="Input.Name"></label>
  15. <input asp-for="Input.Name" class="form-control" />
  16. <span asp-validation-for="Input.Name" class="text-danger"></span>
  17. </div>
  18. <div class="form-group">
  19. <label asp-for="Input.DOB"></label>
  20. <input asp-for="Input.DOB" class="form-control" />
  21. <span asp-validation-for="Input.DOB" class="text-danger"></span>
  22. </div>
  23. <div class="form-group">
  24. <label asp-for="Input.Email"></label>
  25. <input asp-for="Input.Email" class="form-control" />
  26. <span asp-validation-for="Input.Email" class="text-danger"></span>
  27. </div>
  28. <div class="form-group">
  29. <label asp-for="Input.Password"></label>
  30. <input asp-for="Input.Password" class="form-control" />
  31. <span asp-validation-for="Input.Password" class="text-danger"></span>
  32. </div>
  33. <div class="form-group">
  34. <label asp-for="Input.ConfirmPassword"></label>
  35. <input asp-for="Input.ConfirmPassword" class="form-control" />
  36. <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
  37. </div>
  38. <button type="submit" class="btn btn-primary">Register</button>
  39. </form>
  40. </div>
  41. <div class="col-md-6 col-md-offset-2">
  42. <section>
  43. <h4>Use another service to register.</h4>
  44. <hr />
  45. @{
  46. if ((Model.ExternalLogins?.Count ?? 0) == 0)
  47. {
  48. <div>
  49. <p>
  50. There are no external authentication services configured. See
  51. <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
  52. for details on setting up this ASP.NET application to support
  53. logging in via external services.
  54. </p>
  55. </div>
  56. }
  57. else
  58. {
  59. <form id="external-account" asp-page="./ExternalLogin"
  60. asp-route-returnUrl="@Model.ReturnUrl" method="post"
  61. class="form-horizontal">
  62. <div>
  63. <p>
  64. @foreach (var provider in Model.ExternalLogins)
  65. {
  66. <button type="submit" class="btn btn-primary" name="provider"
  67. value="@provider.Name"
  68. title="Log in using your @provider.DisplayName account">
  69. @provider.DisplayName</button>
  70. }
  71. </p>
  72. </div>
  73. </form>
  74. }
  75. }
  76. </section>
  77. </div>
  78. </div>
  79. @section Scripts {
  80. <partial name="_ValidationScriptsPartial" />
  81. }
  1. [AllowAnonymous]
  2. public class RegisterModel : PageModel
  3. {
  4. private readonly SignInManager<WebApp1User> _signInManager;
  5. private readonly UserManager<WebApp1User> _userManager;
  6. private readonly ILogger<RegisterModel> _logger;
  7. private readonly IEmailSender _emailSender;
  8. public RegisterModel(
  9. UserManager<WebApp1User> userManager,
  10. SignInManager<WebApp1User> signInManager,
  11. ILogger<RegisterModel> logger,
  12. IEmailSender emailSender)
  13. {
  14. _userManager = userManager;
  15. _signInManager = signInManager;
  16. _logger = logger;
  17. _emailSender = emailSender;
  18. }
  19. [BindProperty]
  20. public InputModel Input { get; set; }
  21. public string ReturnUrl { get; set; }
  22. public class InputModel
  23. {
  24. [Required]
  25. [DataType(DataType.Text)]
  26. [Display(Name = "Full name")]
  27. public string Name { get; set; }
  28. [Required]
  29. [Display(Name = "Birth Date")]
  30. [DataType(DataType.Date)]
  31. public DateTime DOB { get; set; }
  32. [Required]
  33. [EmailAddress]
  34. [Display(Name = "Email")]
  35. public string Email { get; set; }
  36. [Required]
  37. [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
  38. [DataType(DataType.Password)]
  39. [Display(Name = "Password")]
  40. public string Password { get; set; }
  41. [DataType(DataType.Password)]
  42. [Display(Name = "Confirm password")]
  43. [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
  44. public string ConfirmPassword { get; set; }
  45. }
  46. public void OnGet(string returnUrl = null)
  47. {
  48. ReturnUrl = returnUrl;
  49. }
  50. public async Task<IActionResult> OnPostAsync(string returnUrl = null)
  51. {
  52. returnUrl = returnUrl ?? Url.Content("~/");
  53. if (ModelState.IsValid)
  54. {
  55. var user = new WebApp1User {
  56. Name = Input.Name,
  57. DOB = Input.DOB,
  58. UserName = Input.Email,
  59. Email = Input.Email
  60. };
  61. var result = await _userManager.CreateAsync(user, Input.Password);
  62. if (result.Succeeded)
  63. {
  64. _logger.LogInformation("User created a new account with password.");
  65. var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
  66. var callbackUrl = Url.Page(
  67. "/Account/ConfirmEmail",
  68. pageHandler: null,
  69. values: new { userId = user.Id, code = code },
  70. protocol: Request.Scheme);
  71. await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
  72. $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
  73. await _signInManager.SignInAsync(user, isPersistent: false);
  74. return LocalRedirect(returnUrl);
  75. }
  76. foreach (var error in result.Errors)
  77. {
  78. ModelState.AddModelError(string.Empty, error.Description);
  79. }
  80. }
  81. // If we got this far, something failed, redisplay form
  82. return Page();
  83. }
  84. }

用以下突出显示的标记更新区域/标识/页/帐户/注册. cshtml

  1. @page
  2. @model RegisterModel
  3. @{
  4. ViewData["Title"] = "Register";
  5. }
  6. <h1>@ViewData["Title"]</h1>
  7. <div class="row">
  8. <div class="col-md-4">
  9. <form asp-route-returnUrl="@Model.ReturnUrl" method="post">
  10. <h4>Create a new account.</h4>
  11. <hr />
  12. <div asp-validation-summary="All" class="text-danger"></div>
  13. <div class="form-group">
  14. <label asp-for="Input.Name"></label>
  15. <input asp-for="Input.Name" class="form-control" />
  16. <span asp-validation-for="Input.Name" class="text-danger"></span>
  17. </div>
  18. <div class="form-group">
  19. <label asp-for="Input.DOB"></label>
  20. <input asp-for="Input.DOB" class="form-control" />
  21. <span asp-validation-for="Input.DOB" class="text-danger"></span>
  22. </div>
  23. <div class="form-group">
  24. <label asp-for="Input.Email"></label>
  25. <input asp-for="Input.Email" class="form-control" />
  26. <span asp-validation-for="Input.Email" class="text-danger"></span>
  27. </div>
  28. <div class="form-group">
  29. <label asp-for="Input.Password"></label>
  30. <input asp-for="Input.Password" class="form-control" />
  31. <span asp-validation-for="Input.Password" class="text-danger"></span>
  32. </div>
  33. <div class="form-group">
  34. <label asp-for="Input.ConfirmPassword"></label>
  35. <input asp-for="Input.ConfirmPassword" class="form-control" />
  36. <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
  37. </div>
  38. <button type="submit" class="btn btn-primary">Register</button>
  39. </form>
  40. </div>
  41. </div>
  42. @section Scripts {
  43. <partial name="_ValidationScriptsPartial" />
  44. }

生成项目。

添加自定义用户数据的迁移Add a migration for the custom user data

在 Visual Studio包管理器控制台中:

  1. Add-Migration CustomUserData
  2. Update-Database
  1. dotnet ef migrations add CustomUserData
  2. dotnet ef database update

测试创建、 查看、 下载和删除自定义用户数据Test create, view, download, delete custom user data

测试应用:

  • 注册一个新用户。
  • 查看 /Identity/Account/Manage 页上的自定义用户数据。
  • 从 "/Identity/Account/Manage/PersonalData" 页下载并查看用户个人数据。