Asp.net Identity 2.0 - Unique Email

2020-06-03 09:52发布

My application is MVC5, I tried to allow duplicate email address using the following:

public async Task<ActionResult> AddUser (UserRegisterViewModel userViewModel)
        {
       ......
            if (ModelState.IsValid)
                {
                var user = new ApplicationUser
                {
               ......
                };
                var adminresult = await UserManager.CreateAsync(user);
                var result = await UserManager.AddToRolesAsync(user.Id, user.Profession);
                UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager)
                {
                    RequireUniqueEmail = false
                };
                if (adminresult.Succeeded)
                    {
                     ....
                    return RedirectToAction("VisitInfo", "Visit");
                    }
                if (!adminresult.Succeeded)
                    {
                    var er = adminresult.Errors.FirstOrDefault();
                    ViewBag.Error = er;
                    return View(userViewModel);
                    }

                    return RedirectToAction("VisitInfo", "Visit");
                }               
            return View();
            }

By adding RequireUniqueEmail = false. It did not work, the page is redirected to login page!! My question is could I allow duplicate emails just for this action, and why I get redirected to login page?

3条回答
贪生不怕死
2楼-- · 2020-06-03 09:57

you have to add below lines in configureservices

 services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.User.RequireUniqueEmail = false;

            })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
查看更多
▲ chillily
3楼-- · 2020-06-03 10:00

Thanks to Brendan, I moved

            UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager)
                {
                    RequireUniqueEmail = false
                };

Before:

 var adminresult = await UserManager.CreateAsync(user);
查看更多
老娘就宠你
4楼-- · 2020-06-03 10:04

If you are using the default MVC 5 project template, the proper way is to set the rules in IdentityConfig.cs instead of in the registration controller.

Open App_Start\IdentityConfig.cs and edit this line:

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 = false  //<-- the default is true
    };

    ....<snip>....
查看更多
登录 后发表回答