簡體   English   中英

ASP.NET MVC:控制器未捕獲自定義Identity UserStore類中引發的異常

[英]ASP.NET MVC: Controller not catching exception thrown in custom Identity UserStore class

我正在嘗試在我的ASP.NET MVC項目中實現更改電子郵件功能。 我的應用程序的性質要求每個用戶的電子郵件地址必須唯一。 因此,在我的ASP.NET Identity實現中,我創建了自定義SetEmailAsync()方法,以在電子郵件地址已被使用時引發ArgumentException。 實現如下所示:

class IdentityUserStore
{
    // Unrelated methods omitted for simplicity
    public Task SetEmailAsync(ApplicationUser User, string email)
    {
        var user = UnitOfWork.Users.FindByEmail(email);
        CheckExistingUser(user);
        user.Email = email;
        return Task.FromResult(0);
    }

    private void CheckExistingUser(User user){
        if (user != null)
        {
            throw new ArgumentException("The Email Address is already in use.");
        }    
    }
}

class AccountController : Controller
{
    // Unrelated Methods omitted for simplicity
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Email(ChangeEmailFormModel model)
    {
        ViewBag.ReturnUrl = Url.Action("Email");
        if (ModelState.IsValid)
        {
            try
            {
                var result = await userManager.SetEmailAsync(User.Identity.GetUserId(), model.NewEmail);
                if (result.Succeeded)
                {
                    return RedirectToAction("Email", new { Message = ManageMessageId.ChangeEmailSuccess });
                }
                else
                {
                    result.Errors.Each(error => ModelState.AddModelError("", error));
                }
            }
            catch(ArgumentException ae)
            {
                ModelState.AddModelError("", ae.Message);
            }
        }
        return View();
    }
}

如您所見,IdentityUserStore是用於ASP.NET Identity的UserStore的自定義實現,其中包括更改/設置電子郵件地址的功能。 如果現有User實體已經使用了電子郵件地址,則該類將引發ArgumentException。 並且應該在AccountController類的方法Email()中捕獲此異常,但不會捕獲該異常。 而是,它引發以下錯誤消息:

An exception of type 'System.ArgumentException' occurred in MVCApp.Application.dll but was not handled in user code
Additional information: The Email Address is already in use.

所以我很困惑,我認為如果引發異常,客戶端代碼應該能夠捕獲並處理它。 但這沒有發生,控制器方法未捕獲UserStore引發的異常。 為什么會這樣呢? 它與“ await”語句有關嗎? 有人可以幫忙嗎?

身份框架為您提供了強制實施電子郵件唯一性的選項。 這是在UserValidator<>類中完成的,該類是UserManager的一部分:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    //.. other code
    this.UserValidator = new UserValidator<ApplicationUser>(this)
    {
        RequireUniqueEmail = true,
    };
}

這樣可以防止設置重復的電子郵件。 無需自己構建它。

暫無
暫無

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

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