我创建了Custom UsersyStore,并在CreateAsync
方法中创建了用户。
我想知道如何以及在何处根据电子邮件检查用户是否已存在?
CreateAsync
方法只返回Task。但我如何检查用户是否已经存在。目前它正在根据Id
答案 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);