为什么 `UserManager.ConfirmEmailAsync` 会针对无效用户抛出异常?
Why does `UserManager.ConfirmEmailAsync` throw for an invalid user?
根据我在 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
。
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);
}
您可以看到当使用 FindByIdAsync(userId)
找不到用户时抛出 InvalidOperationException
。
所以这种行为是设计使然。
根据我在 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
。
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);
}
您可以看到当使用 FindByIdAsync(userId)
找不到用户时抛出 InvalidOperationException
。
所以这种行为是设计使然。