.net核心身份,获取特定的注册错误条件

时间:2018-08-03 08:47:50

标签: c# asp.net-core-2.0 asp.net-core-identity

我希望使用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?
}

1 个答案:

答案 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可能还需要检查。