[英]How to add a IdentityUser IdentityResult error in ASP.Net Core for a unique email address
My "User" class inherits from "IdentityUser" and I want to make the EmailAddress unique. 我的“用户”类继承自“ IdentityUser”,我想使EmailAddress唯一。 BUT instead of creating a unique property like this
但是不要像这样创建一个独特的属性
builder.Entity<User>()
.HasIndex(u => u.Email).IsUnique();
in the model builder that throws an exception when I try to register a duplicate email address in the method below, I'd like it to return a IdentityResult error, just like it does when I have a duplicate username. 在我尝试在下面的方法中注册重复的电子邮件地址时引发异常的模型构建器中,我希望它返回IdentityResult错误,就像我有重复的用户名时一样。 Some how Identity forgot to include a uniqueness for the email field!?
一些身份如何忘记为电子邮件字段添加唯一性!?
My register method where "result.Succeeded" is false if the username is taken/used and an IEnumerable of IdentityErrors, in "result.errors". 我的注册方法,其中“ result.Succeeded”为假(如果已使用/使用了用户名)和“ result.errors”中的IEnumerable of IdentityErrors。 I'd like to get the same type of error from a duplicate email.
我想从重复的电子邮件中得到相同类型的错误。 Is this possible?
这可能吗?
[HttpPost("register")]
public async Task<IActionResult> Register(UserForRegisterDto userForRegisterDto)
{
var userToCreate = _mapper.Map<User>(userForRegisterDto);
var result = await _userManager.CreateAsync(userToCreate, userForRegisterDto.Password);
var userToReturn = _mapper.Map<UserForDetailedDto>(userToCreate);
if (result.Succeeded)
{
return CreatedAtRoute("GetUser", new { controller = "Users", id = userToCreate.Id }, userToReturn);
}
return BadRequest(result.Errors);
}
This is already supported, using RequireUniqueEmail
, which defaults to false
. 使用
RequireUniqueEmail
已支持此RequireUniqueEmail
,默认为false
。 Here's an example of how to set it to true
, taken from the docs and modified accordingly: 这是一个如何将其设置为
true
的示例,该示例取自文档并进行了相应修改:
services.Configure<IdentityOptions>(options =>
{
options.User.RequireUniqueEmail = true;
});
You can achieve the same thing with the call to AddIdentity
(or whichever variation you're using). 您可以通过调用
AddIdentity
(或使用的任何变体)来实现相同的AddIdentity
。 Here's an example of that approach: 这是该方法的示例:
services.AddIdentity<User, Role>(options =>
{
options.User.RequireUniqueEmail = true;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.