[英].NET Core UserManager CreateAsync leaves UserName/Email/PhoneNumber always null
NET Core 應用程序為一些額外字段實現自定義IdentutyUser
邏輯。
我設法使用CreateAsync
創建了一個用戶,但字段UserName
、 Email
和PhoneNumber
總是被忽略。 它們的規范化版本( NormalizedUserName
、 NormalizedEmail
和NormalizedPhoneNumber
(最后一個是由我創建的,因為任何不可為空的值都必須是唯一的))創建成功但始終大寫。
控制器代碼:
[HttpPost]
[AllowAnonymous]
[Route("Registration")]
public async Task<IActionResult> UserRegistration(ApplicationUserModel model)
{
var applicationUser = new ApplicationUser()
{
UserName = model.UserName,
Email = model.Email,
PhoneNumber = model.PhoneNumber,
FirstName = model.FirstName,
// Other fields that are being inserted normally...
};
IdentityResult result = await _userManager.CreateAsync(applicationUser, model.Password);
try
{
return Ok(result);
}
catch (Exception ex)
{
throw ex;
}
}
如果它有助於有問題的字段被ApplicationUser
模型類覆蓋:
public class ApplicationUser : IdentityUser
{
[Column("UserName", TypeName = "nvarchar(24)")]
[Required(ErrorMessage = "UN_REQUIRED")]
[StringLength(24, ErrorMessage = "UN_LENGTH", MinimumLength = 3)]
[RegularExpression(@"[A-Za-z]+(?:[A-Za-z0-9-_])+(?:[_-]\w+)?$", ErrorMessage = "UN_INVALID")]
public override string UserName { get; set; }
[Column("Email", TypeName = "nvarchar(64)")]
[Required(ErrorMessage = "EM_REQUIRED")]
[StringLength(64, ErrorMessage = "EM_LENGTH", MinimumLength = 13)]
[EmailAddress(ErrorMessage = "EM_INVALID")]
public override string Email { get; set; }
[Column("PhoneNumber", TypeName = "nvarchar(15)")]
[Phone(ErrorMessage = "PN_INVALID")]
public override string PhoneNumber { get; set; }
...
}
我在Startup.cs
也有這個代碼:
services.Configure<IdentityOptions>(options => {
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
options.User.RequireUniqueEmail = true;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
});
我該怎么做才能將相應的值與其余值一起插入到數據庫中?
添加自定義屬性后,您應該在 ConfigureServices 中使用新的ApplicationUser
:
services.AddDefaultIdentity<ApplicationUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
和ApplicationDbContext
:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
並確認您在控制器中使用新的 ApplicationUser 注入 UserManager:
private readonly UserManager<ApplicationUser> _userManager;
最后Add-migration xx
, update-database
讓 ef 在AspNetUsers
表中創建列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.