使用中的错误案例列表_userManager.CreateAsync(用户,密码)

Tân*_*Tân 4 c# asp.net asp.net-mvc asp.net-core

UserManager.CreateAsync方法(TUser,String)没有提及错误。

在控制器中,我编辑以下内容:

public async Task<ObjectResult> Register(RegisterViewModel model, string returnUrl = null)
{
    IDictionary<string, object> value = new Dictionary<string, object>();
    value["Success"] = false;
    value["ReturnUrl"] = returnUrl;

    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { Id = Guid.NewGuid().ToString(), UserName = model.Email, Email = model.Email };

        var result = await _userManager.CreateAsync(user, model.Password);

        if (result.Succeeded)
        {
            await _signInManager.SignInAsync(user, isPersistent: false);
            value["Success"] = true;
        }
        else
        {
            value["ErrorMessage"] = result.Errors;
        }    
    }

    return new ObjectResult(value);
}
Run Code Online (Sandbox Code Playgroud)

在客户中:

$scope.registerForm_submit = function ($event, account) {
    $event.preventDefault();

    if (registerForm.isValid(account)) {

        // registerForm.collectData returns new FormData() which contains
        // email, password, confirmpassword, agreement, returnurl...

        let formData = registerForm.collectData(account),                
            xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function () {
            if (xhttp.readyState === XMLHttpRequest.DONE) {
                let data = JSON.parse(xhttp.responseText);

                if (data['Success']) {
                    window.location = '/'
                } else {                        
                    if (data['ErrorMessage'][0]['code'] === 'DuplicateUserName') {
                        let li = angular.element('<li/>').text(`Email ${account['email']} already exists.`);
                        angular.element('div[data-valmsg-summary=true] ul').html(li);
                    }
                }
            }
        }

        xhttp.open('POST', '/account/register');
        xhttp.send(formData);
    }
};
Run Code Online (Sandbox Code Playgroud)

我试图用现有的电子邮件注册新帐户并获得代码:

data['ErrorMessage'][0]['code'] === 'DuplicateUserName'
Run Code Online (Sandbox Code Playgroud)

我的问题:如何检查其他情况?

B12*_*ter 11

对于 ASP.NET Core,您可以IdentityErrorDescriber在命名空间下的类中找到不同的错误类型Microsoft.AspNetCore.Identity

如您所见,错误代码是通过 生成的nameof(),例如:

Code = nameof(DuplicateUserName)
Run Code Online (Sandbox Code Playgroud)

因此,您也可以将其用于您的案例:

data['ErrorMessage'][0]['code'] == nameof(IdentityErrorDescriber.DuplicateUserName)
Run Code Online (Sandbox Code Playgroud)

这样您就不必按照问题的另一个答案中的建议整理错误代码列表。


Tie*_* T. 6

可在https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.Core/Resources.Designer.cs中找到ASP.NET Identity中定义的错误代码-我已将其提取到此文件中清单:

  • DefaultError
  • 重复邮件
  • 重复名称
  • 存在外部登录
  • 不合规电邮
  • 令牌无效
  • 无效的用户名
  • LockoutNotEnabled
  • NoTokenProvider
  • NoTwoFactorProvider
  • 密码不匹配
  • 密码要求数字
  • 密码要求降低
  • 密码要求非字母或数字
  • PasswordRequireUpper
  • 密码太短
  • 属性太短
  • RoleNotFound
  • StoreNotIQueryableRoleStore
  • StoreNotIQueryableUserStore
  • StoreNotIUserClaimStore
  • StoreNotIUserConfirmationStore
  • StoreNotIUserEmailStore
  • StoreNotIUserLockoutStore
  • StoreNotIUserLoginStore
  • StoreNotIUserPasswordStore
  • StoreNotIUserPhoneNumberStore
  • StoreNotIUserRoleStore
  • StoreNotIUserSecurityStampStore
  • StoreNotIUserTwoFactorStore
  • UserAlreadyHasPassword
  • UserAlreadyInRole
  • UserIdNotFound
  • UserNameNotFound
  • UserNotInRole

ASP.NET Core Identity已定义以下代码:

  • DefaultError
  • 并发失败
  • 密码不匹配
  • 令牌无效
  • 登录已关联
  • 无效的用户名
  • 不合规电邮
  • DuplicateUserName
  • 重复邮件
  • InvalidRoleName
  • DuplicateRoleName
  • UserAlreadyHasPassword
  • UserLockoutNotEnabled
  • UserAlreadyInRole
  • UserNotInRole
  • 密码太短
  • 密码要求非字母数字
  • 密码要求数字
  • 密码要求更低
  • PasswordRequiresUpper

因此,可能并非所有以前的错误代码都会真正显示在IdentityResult中。我都不用,因此这只是我从可用的源代码中收集的内容。买者自负...

似乎应该在某处记录这样的内容...

我喜欢在一个地方定义这种性质的字符串,因此我通常会执行以下操作:

public class IdentityErrorCodes
{
    public const string DefaultError                    = "DefaultError";
    public const string ConcurrencyFailure              = "ConcurrencyFailure";
    public const string PasswordMismatch                = "PasswordMismatch";
    public const string InvalidToken                    = "InvalidToken";
    public const string LoginAlreadyAssociated          = "LoginAlreadyAssociated";
    public const string InvalidUserName                 = "InvalidUserName";
    public const string InvalidEmail                    = "InvalidEmail";
    public const string DuplicateUserName               = "DuplicateUserName";
    public const string DuplicateEmail                  = "DuplicateEmail";
    public const string InvalidRoleName                 = "InvalidRoleName";
    public const string DuplicateRoleName               = "DuplicateRoleName";
    public const string UserAlreadyHasPassword          = "UserAlreadyHasPassword";
    public const string UserLockoutNotEnabled           = "UserLockoutNotEnabled";
    public const string UserAlreadyInRole               = "UserAlreadyInRole";
    public const string UserNotInRole                   = "UserNotInRole";
    public const string PasswordTooShort                = "PasswordTooShort";
    public const string PasswordRequiresNonAlphanumeric = "PasswordRequiresNonAlphanumeric";
    public const string PasswordRequiresDigit           = "PasswordRequiresDigit";
    public const string PasswordRequiresLower           = "PasswordRequiresLower";
    public const string PasswordRequiresUpper           = "PasswordRequiresUpper";

    public static string[] All = { 
        DefaultError,
        ConcurrencyFailure,
        PasswordMismatch,
        InvalidToken,
        LoginAlreadyAssociated,
        InvalidUserName,
        InvalidEmail,
        DuplicateUserName,
        DuplicateEmail,
        InvalidRoleName,
        DuplicateRoleName,
        UserAlreadyHasPassword,
        UserLockoutNotEnabled,
        UserAlreadyInRole,
        UserNotInRole,
        PasswordTooShort,
        PasswordRequiresNonAlphanumeric,
        PasswordRequiresDigit,
        PasswordRequiresLower,
        PasswordRequiresUpper 
    };
}
Run Code Online (Sandbox Code Playgroud)

这样可以使您在用作查询的键中保持一致,并且最后一个字段All可以在必要时为您提供一个可以枚举的数组。

使用您的代码,您可以执行以下操作:

if(data['ErrorMessage'][0]['code'] == IdentityErrorCodes.DuplicateUserName)
{
}
Run Code Online (Sandbox Code Playgroud)

等等。