简体   繁体   English

正在使用的错误案例列表_userManager.CreateAsync(user,password)

[英]List of error cases in use _userManager.CreateAsync(user, password)

UserManager.CreateAsync Method (TUser, String) doesn't mention about errors. UserManager.CreateAsync方法(TUser,String)未提及错误。

In controller, I jsut edit something like: 在控制器中,我jsut编辑类似的东西:

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);
}

In client: 在客户端:

$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);
    }
};

I've tried to register new account with an existing email and got the code: 我尝试使用现有电子邮件注册新帐户并获取代码:

data['ErrorMessage'][0]['code'] === 'DuplicateUserName'

My question: how to check other cases? 我的问题:如何检查其他案件?

The error codes defined in ASP.NET Identity are found at https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.Core/Resources.Designer.cs - I've extracted them out to this list: ASP.NET身份中定义的错误代码位于https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.Core/Resources.Designer.cs - 我已将它们解压缩到此列表:

  • DefaultError DefaultError
  • DuplicateEmail DuplicateEmail
  • DuplicateName DuplicateName
  • ExternalLoginExists ExternalLoginExists
  • InvalidEmail 不合规电邮
  • InvalidToken 令牌无效
  • InvalidUserName 无效的用户名
  • LockoutNotEnabled LockoutNotEnabled
  • NoTokenProvider NoTokenProvider
  • NoTwoFactorProvider NoTwoFactorProvider
  • PasswordMismatch 密码不符合
  • PasswordRequireDigit PasswordRequireDigit
  • PasswordRequireLower PasswordRequireLower
  • PasswordRequireNonLetterOrDigit PasswordRequireNonLetterOrDigit
  • PasswordRequireUpper PasswordRequireUpper
  • PasswordTooShort 密码太短
  • PropertyTooShort PropertyTooShort
  • RoleNotFound RoleNotFound
  • StoreNotIQueryableRoleStore StoreNotIQueryableRoleStore
  • StoreNotIQueryableUserStore StoreNotIQueryableUserStore
  • StoreNotIUserClaimStore StoreNotIUserClaimStore
  • StoreNotIUserConfirmationStore StoreNotIUserConfirmationStore
  • StoreNotIUserEmailStore StoreNotIUserEmailStore
  • StoreNotIUserLockoutStore StoreNotIUserLockoutStore
  • StoreNotIUserLoginStore StoreNotIUserLoginStore
  • StoreNotIUserPasswordStore StoreNotIUserPasswordStore
  • StoreNotIUserPhoneNumberStore StoreNotIUserPhoneNumberStore
  • StoreNotIUserRoleStore StoreNotIUserRoleStore
  • StoreNotIUserSecurityStampStore StoreNotIUserSecurityStampStore
  • StoreNotIUserTwoFactorStore StoreNotIUserTwoFactorStore
  • UserAlreadyHasPassword UserAlreadyHasPassword
  • UserAlreadyInRole UserAlreadyInRole
  • UserIdNotFound UserIdNotFound
  • UserNameNotFound UserNameNotFound
  • UserNotInRole UserNotInRole

ASP.NET Core Identity has these codes defined: ASP.NET Core Identity定义了以下代码:

  • DefaultError DefaultError
  • ConcurrencyFailure ConcurrencyFailure
  • PasswordMismatch 密码不符合
  • InvalidToken 令牌无效
  • LoginAlreadyAssociated LoginAlreadyAssociated
  • InvalidUserName 无效的用户名
  • InvalidEmail 不合规电邮
  • DuplicateUserName DuplicateUserName
  • DuplicateEmail DuplicateEmail
  • InvalidRoleName InvalidRoleName
  • DuplicateRoleName DuplicateRoleName
  • UserAlreadyHasPassword UserAlreadyHasPassword
  • UserLockoutNotEnabled UserLockoutNotEnabled
  • UserAlreadyInRole UserAlreadyInRole
  • UserNotInRole UserNotInRole
  • PasswordTooShort 密码太短
  • PasswordRequiresNonAlphanumeric PasswordRequiresNonAlphanumeric
  • PasswordRequiresDigit PasswordRequiresDigit
  • PasswordRequiresLower PasswordRequiresLower
  • PasswordRequiresUpper PasswordRequiresUpper

So, it's possible that not all of the former error codes will actually show up in an IdentityResult. 因此,有可能并非所有以前的错误代码都会实际显示在IdentityResult中。 I don't use either, so this is just what I gather from skimming the available source code. 我也没有使用,所以这就是我从浏览可用源代码中收集到的内容。 Caveat emptor... 买者自负...

Seems like this should be documented somewhere... 似乎这应该在某处记录......

I like to have strings of this nature defined in one place, so I typically do something like: 我喜欢在一个地方定义这种性质的字符串,所以我通常会这样做:

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 
    };
}

This lets you be consistent in the keys you're using as lookups, and the last field, All , gives you an array you can enumerate through, if necessary. 这使您可以在用作查找的键中保持一致,最后一个字段All为您提供可以枚举的数组(如有必要)。

Using your code, you can do this: 使用您的代码,您可以这样做:

if(data['ErrorMessage'][0]['code'] == IdentityErrorCodes.DuplicateUserName)
{
}

And so on. 等等。

For ASP.NET Core you can find the different error types in the IdentityErrorDescriber class under the namespace Microsoft.AspNetCore.Identity . 对于ASP.NET Core, 您可以在名称空间Microsoft.AspNetCore.Identity下的IdentityErrorDescriber类中找到不同的错误类型。

As you can see , the error codes are generated via nameof() , eg: 如您所见 ,错误代码是通过nameof()生成的,例如:

Code = nameof(DuplicateUserName)

So you could also use that for your cases: 所以你也可以在你的情况下使用它:

data['ErrorMessage'][0]['code'] == nameof(IdentityErrorDescriber.DuplicateUserName)

This way you don't have to curate a list of error codes as suggested in another answer to your question. 这样,您就不必按照问题的另一个答案中的建议策划错误代码列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 UserManager.CreateAsync(用户,密码)陷入无限循环 - UserManager.CreateAsync(user, password) stuck in infinite loop Foo在UserManager.CreateAsync上的关系栏错误上的角色冲突更改 - Conflicting changes to the role of Foo on relationship Bar error on UserManager.CreateAsync ASP.Net.Core userManager.CreateAsync - ASP.Net.Core userManager.CreateAsync UserManager.CreateAsync 不生成 Id - UserManager.CreateAsync does not generate Id 名称不能为null或为空:_userManager.CreateAsync - Name cannot be null or empty: _userManager.CreateAsync UserManager.CreateAsync。成功总是返回false - UserManager.CreateAsync .Success always returns false UserManager.CreateAsync不会在ApplicationUser中保存添加的属性 - UserManager.CreateAsync does not save added properties in ApplicationUser 如何删除使用UserManager.CreateAsync创建的用户 - How to delete users that were created with UserManager.CreateAsync 等待 UserManager.CreateAsync 寻找不存在的列 - await UserManager.CreateAsync looking for column that does not exist Asp .Net Core 单元测试模拟 UserManager.CreateAsync 并返回标识结果 - Asp .Net Core Unit Test Mock UserManager.CreateAsync and return Identity Result
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM