Asp.net 身份 2.0 - 唯一电子邮件



我的应用程序是MVC5,我尝试使用以下方法允许重复的电子邮件地址:

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

通过添加 RequireUniqueEmail = false。它不起作用,页面被重定向到登录页面!!我的问题是我可以只允许此操作的重复电子邮件吗,为什么我会被重定向到登录页面?

如果使用默认的 MVC 5 项目模板,正确的方法是在 IdentityConfig.cs 中设置规则,而不是在注册控制器中设置规则

打开App_StartIdentityConfig.cs并编辑此行:

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>....

您必须在配置服务中添加以下行

 services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.User.RequireUniqueEmail = false;
            })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

感谢布兰登,我搬家了

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

以前:

 var adminresult = await UserManager.CreateAsync(user);

对于.NET Core.NET5 +,需要将其作为选项添加到IServiceCollection

services.AddIdentityCore<AppUser>(opt =>
{
    opt.User.RequireUniqueEmail = true;
})
    .AddEntityFrameworkStores<DataContext>();

相关内容

  • 没有找到相关文章

最新更新