为什么`UserManager.ConfirmEmailAsync`会为无效用户投掷?

时间:2015-10-04 16:51:10

标签: asp.net-mvc asp.net-mvc-5 asp.net-identity

鉴于ConfirmEmail中的代码:

var result = await UserManager.ConfirmEmailAsync(userId, code);
if (result.Succeeded)
{
    model.Message = "Thank you for confirming your email.";
    model.IsConfirmed = true;
    return View(model);
}

基于标准MVC 5项目模板的代码,我希望无效的用户导致result.Succeeded == false,而不是让ConfirmEmailAsync抛出InvalidOperationException

1 个答案:

答案 0 :(得分:2)

UserManager.ConfirmEmailAsync的源代码是:

public virtual async Task<IdentityResult> ConfirmEmailAsync(TKey userId, string token)
{
    ThrowIfDisposed();
    var store = GetEmailStore();
    var user = await FindByIdAsync(userId).ConfigureAwait(false);
    if (user == null)
    {
        throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Resources.UserIdNotFound, userId));
    }
    if (!await VerifyUserTokenAsync(userId, "Confirmation", token))
    {
        return IdentityResult.Failed(Resources.InvalidToken);
    }
    await store.SetEmailConfirmedAsync(user, true).ConfigureAwait(false);
    return await UpdateAsync(user).ConfigureAwait(false);
}

您可以看到使用InvalidOperationException找不到用户时会引发FindByIdAsync(userId)

所以这种行为是设计的。