我希望使用UserManager返回的特定错误条件进行测试/交易,例如:由于文件中已有用户名而导致注册失败等
var user = new SiteUser() { UserName = username, Email = RegisterViewModel.Email };
var result = await _userManager.CreateAsync(user, RegisterViewModel.Password);
if (!result.Succeeded)
{
// here I want to test for specific error conditions
// eg: username already on file, etc
// how can I do this?
}
答案 0 :(得分:1)
IdentityResult
包含一个Errors
属性,该属性的类型为IEnumerable<IdentityError>
。 IdentityError
本身包含一个Code
属性和一个Description
属性。这意味着您的OP中的result
变量具有一个Errors
属性,该属性描述了发生的特定错误。
IdentityErrorDescriber
用于生成IdentityError
的实例。这是来自source的示例:
public virtual IdentityError DuplicateUserName(string userName)
{
return new IdentityError
{
Code = nameof(DuplicateUserName),
Description = Resources.FormatDuplicateUserName(userName)
};
}
IdentityErrorDescriber
的注入方式与UserManager
相同。这意味着您可以将其作为控制器构造函数中的依赖项(例如),并在以后使用,就像这样(假设_errorDescriber
已在构造函数中创建并设置):
if (!result.Succeeded)
{
// DuplicateUserName(...) requires the UserName itself so it can add it in the
// Description. We don't care about that so just provide null.
var duplicateUserNameCode = _errorDescriber.DuplicateUserName(null).Code;
// Here's another option that's less flexible but removes the need for _errorDescriber.
// var duplicateUserNameCode = nameof(IdentityErrorDescriber.DuplicateUserName);
if (result.Errors.Any(x => x.Code == duplicateUserNameCode))
{
// Your code for handling DuplicateUserName.
}
}
有多种方法可以获取要测试的Code
值并自己进行检查-这只是一个示例,对于您可能希望对代码和错误本身。
如果您有兴趣,请在源头上找到link,将DuplicateUserName
错误添加到您返回的IdentityResult
中。
我在这里只谈论了DuplicateUserName
,但是还有其他IdentityErrorDescriber
的值,例如InvalidEmail
可能还需要检查。