[英].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.