Asp.Net Identity save user without email

前端 未结 5 929
旧时难觅i
旧时难觅i 2021-01-31 03:24

I want to save user without email, like this:

var user = new ApplicationUser { UserName = model.Name };
var result = await UserManager.CreateAsync(user);
         


        
5条回答
  •  悲&欢浪女
    2021-01-31 04:26

    I know this is old, but I disagree with the accepted answer, since the question is tagged as asp.net-identity-2. For the benefit of future readers, ASP.NET Identity 2.0 has a very simple solution to this problem:

    public class ApplicationUserManager : UserManager
    {
        ...snip...
        public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context) 
        {
            var manager = new ApplicationUserManager(new UserStore(context.Get()));
            manager.UserValidator = new UserValidator(manager)
            {
                // This disables the validation check on email addresses
                RequireUniqueEmail = false
            };
            ...snip...
        }
    }
    

    In UserValidator, the Task ValidateAsync(T item) implementation checks this flag and determines if it should run email validation:

    if (this.RequireUniqueEmail)
    {
        await this.ValidateEmail(item, list);
    }
    

    Since you want to save users without an email address, this is how you should do it.

    CAUTION: This should only be used when email addresses are not collected. If you want to collect and validate email addresses, but make them optional during registration, you should use a custom IIdentityValidator.

提交回复
热议问题