简体   繁体   English

ASP.NET MVC:控制器未捕获自定义Identity UserStore类中引发的异常

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

I am trying to implement changing email functionality in my ASP.NET MVC project. 我正在尝试在我的ASP.NET MVC项目中实现更改电子邮件功能。 The nature of my application requires that email address be unique with each user. 我的应用程序的性质要求每个用户的电子邮件地址必须唯一。 So in my ASP.NET Identity implementation I created custom SetEmailAsync() method to throw an ArgumentException when the email address is already in use. 因此,在我的ASP.NET Identity实现中,我创建了自定义SetEmailAsync()方法,以在电子邮件地址已被使用时引发ArgumentException。 The implementation is shown below: 实现如下所示:

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

As you can see, The IdentityUserStore is a custom implementation of UserStore for ASP.NET Identity, which includes the functionality to change/set email address. 如您所见,IdentityUserStore是用于ASP.NET Identity的UserStore的自定义实现,其中包括更改/设置电子邮件地址的功能。 This class throws an ArgumentException if email address is already being used by an existing User entity. 如果现有User实体已经使用了电子邮件地址,则该类将引发ArgumentException。 And this exception is supposed to be caught in the AccountController class' method Email(), but it doesnt get caught. 并且应该在AccountController类的方法Email()中捕获此异常,但不会捕获该异常。 Instead, it throws this following error message: 而是,它引发以下错误消息:

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.

So I am totally confused, I thought if an exception is thrown, the client code should be able to catch and handle it. 所以我很困惑,我认为如果引发异常,客户端代码应该能够捕获并处理它。 But this isnt happening, the exception thrown by the UserStore is not caught by controller method. 但这没有发生,控制器方法未捕获UserStore引发的异常。 Why is this happening? 为什么会这样呢? Does it have something to do with the 'await' statement? 它与“ await”语句有关吗? Can anyone help? 有人可以帮忙吗?

Identity framework provides you an option to enforce email uniqueness. 身份框架为您提供了强制实施电子邮件唯一性的选项。 This is done in UserValidator<> class which is a part of UserManager : 这是在UserValidator<>类中完成的,该类是UserManager的一部分:

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

This will prevent duplicate emails to be set. 这样可以防止设置重复的电子邮件。 And no need in building it yourself. 无需自己构建它。

暂无
暂无

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

相关问题 捕获CustomAuthorizeAttribute ASP.NET MVC 4引发的异常 - catching exception thrown By CustomAuthorizeAttribute ASP.NET MVC 4 捕获ASP.NET WebService上WebMethod引发的自定义异常 - Catching a custom Exception thrown by a WebMethod on ASP.NET WebService 具有自定义UserStore的Asp.Net身份,无法访问重载 - Asp.Net Identity with custom UserStore, overload inaccessible 在 ASP.NET 5 中使用自定义 UserStore 和 RoleStore - Using a Custom UserStore and RoleStore in ASP.NET 5 从Asp.net中的DbObject转换或创建UserStore中的TUser mvc 5标识“Connot隐式转换类型” - Convert or Create TUser in UserStore From a DbObject in Asp.net mvc 5 Identity “Connot Implicitly convert type” 自定义ASP.NET Identity 2.0 UserStore - 是否实现了所需的所有接口? - Custom ASP.NET Identity 2.0 UserStore - Is implementing all interfaces required? 在ASP.NET MVC和C#中使用自定义异常类时未捕获异常 - Exception not catching when using Custom Exception classes in ASP.NET MVC and C# 为什么在ASP.NET Identity的`UserStore`中有这么多的存储库? - Why so many repositories in ASP.NET Identity's `UserStore`? ASP.NET Identity UserStore:为什么要返回Task? - ASP.NET Identity UserStore: Why return Task? ASP.NET Identity UserStore中的GetNormalizedUserNameAsync和SetNormalizedUserNameAsync函数的说明 - Explanation of GetNormalizedUserNameAsync and SetNormalizedUserNameAsync functions in ASP.NET Identity UserStore
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM