用户注册以根据电子邮件检查用户是否存在 - Custom UserStore

时间:2017-06-29 07:17:53

标签: c# .net asp.net-mvc asp.net-identity asp.net-identity-2

我创建了Custom UsersyStore,并在CreateAsync方法中创建了用户。

我想知道如何以及在何处根据电子邮件检查用户是否已存在?

CreateAsync方法只返回Task。但我如何检查用户是否已经存在。目前它正在根据Id

创建新用户

1 个答案:

答案 0 :(得分:1)

您必须在创建之前验证用户(和密码)。假设使用Identity Framework模板,您可以使用类似的方法来验证密码和用户:

var identityResult = await userManager.PasswordValidator.ValidateAsync(account.Password);
if (!identityResult.Succeeded)
    return SomeError(identityResult);

// Validate the new user BEFORE creating in the database.
identityResult = await userManager.UserValidator.ValidateAsync(appUser);
if (!identityResult.Succeeded)
    return SomeError(identityResult);

identityResult = await userManager.CreateAsync(appUser, account.Password);
if (!identityResult.Succeeded)
    return SomeError(identityResult);

您可以在以下位置设置验证选项:

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
    var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));

    // Configure validation logic for usernames
    manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
        AllowOnlyAlphanumericUserNames = false,
        RequireUniqueEmail = true
    };

    // ...
}

请注意,这将假设用户名是电子邮件。如果您不想要这个,那么您应该设置RequireUniqueEmail = false。但我认为在这种情况下它不会检查唯一的电子邮件。因此,您可以添加此行以检查唯一的电子邮件:

var isUniqueEmail = (await userManager.FindByEmailAsync(email) == null);