.net core Identity,获取特定的注册错误条件

use*_*625 4 c# asp.net-core asp.net-core-identity asp.net-core-2.0

我希望测试/处理从 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?
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*kin 5

IdentityResult包含一个Errors属性,其类型为IEnumerable<IdentityError>IdentityError本身既包含Code属性又Description包含属性。这意味着resultOP 中的变量具有Errors描述发生的特定错误的属性。

IdentityErrorDescriber用于生成 的实例IdentityError这是来自来源的示例:

public virtual IdentityError DuplicateUserName(string userName)
{
    return new IdentityError
    {
        Code = nameof(DuplicateUserName),
        Description = Resources.FormatDuplicateUserName(userName)
    };
}
Run Code Online (Sandbox Code Playgroud)

IdentityErrorDescriber以同样的方式注入到 DI 系统中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.
    }
}
Run Code Online (Sandbox Code Playgroud)

有许多不同的方法可以获取Code您想要测试的值并自行进行检查 - 这只是一个示例,对于您可能想要对代码和错误本身进行的自定义来说,它是相当安全的。

如果您有兴趣,这里有一个源链接DuplicateUserName,可以将错误添加到IdentityResult您返回的信息中。

我只在这里讨论过DuplicateUserName,但还有其他IdentityErrorDescriber值,例如InvalidEmail您可能还想检查一下。