簡體   English   中英

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

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

UserManager.CreateAsync方法(TUser,String)未提及錯誤。

在控制器中,我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);
}

在客戶端:

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

我嘗試使用現有電子郵件注冊新帳戶並獲取代碼:

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

我的問題:如何檢查其他案件?

ASP.NET身份中定義的錯誤代碼位於https://aspnetidentity.codeplex.com/SourceControl/latest#src/Microsoft.AspNet.Identity.Core/Resources.Designer.cs - 我已將它們解壓縮到此列表:

  • DefaultError
  • DuplicateEmail
  • DuplicateName
  • ExternalLoginExists
  • 不合規電郵
  • 令牌無效
  • 無效的用戶名
  • LockoutNotEnabled
  • NoTokenProvider
  • NoTwoFactorProvider
  • 密碼不符合
  • PasswordRequireDigit
  • PasswordRequireLower
  • PasswordRequireNonLetterOrDigit
  • PasswordRequireUpper
  • 密碼太短
  • PropertyTooShort
  • RoleNotFound
  • StoreNotIQueryableRoleStore
  • StoreNotIQueryableUserStore
  • StoreNotIUserClaimStore
  • StoreNotIUserConfirmationStore
  • StoreNotIUserEmailStore
  • StoreNotIUserLockoutStore
  • StoreNotIUserLoginStore
  • StoreNotIUserPasswordStore
  • StoreNotIUserPhoneNumberStore
  • StoreNotIUserRoleStore
  • StoreNotIUserSecurityStampStore
  • StoreNotIUserTwoFactorStore
  • UserAlreadyHasPassword
  • UserAlreadyInRole
  • UserIdNotFound
  • UserNameNotFound
  • UserNotInRole

ASP.NET Core Identity定義了以下代碼:

  • DefaultError
  • ConcurrencyFailure
  • 密碼不符合
  • 令牌無效
  • LoginAlreadyAssociated
  • 無效的用戶名
  • 不合規電郵
  • DuplicateUserName
  • DuplicateEmail
  • InvalidRoleName
  • DuplicateRoleName
  • UserAlreadyHasPassword
  • UserLockoutNotEnabled
  • UserAlreadyInRole
  • UserNotInRole
  • 密碼太短
  • PasswordRequiresNonAlphanumeric
  • PasswordRequiresDigit
  • PasswordRequiresLower
  • 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 
    };
}

這使您可以在用作查找的鍵中保持一致,最后一個字段All為您提供可以枚舉的數組(如有必要)。

使用您的代碼,您可以這樣做:

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

等等。

對於ASP.NET Core, 您可以在名稱空間Microsoft.AspNetCore.Identity下的IdentityErrorDescriber類中找到不同的錯誤類型。

如您所見 ,錯誤代碼是通過nameof()生成的,例如:

Code = nameof(DuplicateUserName)

所以你也可以在你的情況下使用它:

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

這樣,您就不必按照問題的另一個答案中的建議策划錯誤代碼列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM