在Asp.Net核心身份中需要唯一的电话号码

问题描述 投票:5回答:2

在Asp.Net核心身份框架中,我可以通过设置RequireUniqueEmail = true轻松地要求唯一的电子邮件地址。

有没有办法对用户的电话号码做同样的事情?请注意,我不想要求确认的电话号码才能登录。用户无需输入电话号码,但如果有,则必须是唯一的。

asp.net-core unique asp.net-core-identity
2个回答
2
投票

您可以尝试这一点,基本上首先在Db级别强制执行,然后在Manager级别执行适当的检查。

在DbContext,我声明了用户名和电子邮件属性的索引和唯一性。

// ================== Customizing IdentityCore Tables ================== //
        // https://stackoverflow.com/questions/30114751/renaming-identity-tables-with-ef6-migrations-failing

        builder.Entity<User>().ToTable("Users").Property(p => p.Id).HasColumnName("Id").ValueGeneratedOnAdd();
        builder.Entity<User>(entity =>
        {
            entity.HasIndex(u => u.UserName).IsUnique();
            entity.HasIndex(u => u.NormalizedUserName).IsUnique();
            entity.HasIndex(u => u.Email).IsUnique();
            entity.HasIndex(u => u.NormalizedEmail).IsUnique();

            entity.Property(u => u.Rating).HasDefaultValue(0).IsRequired();
            entity.HasMany(u => u.UserRoles).WithOne(ur => ur.User)
                .HasForeignKey(ur => ur.UserId).OnDelete(DeleteBehavior.Restrict);
            entity.HasMany(u => u.UserClaims).WithOne(uc => uc.User)
                .HasForeignKey(uc => uc.UserId).OnDelete(DeleteBehavior.Restrict);
        });

对于Manager级代码:

/// <summary>
        /// Sets the <paramref name="email"/> address for a <paramref name="user"/>.
        /// </summary>
        /// <param name="user">The user whose email should be set.</param>
        /// <param name="email">The email to set.</param>
        /// <returns>
        /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
        /// of the operation.
        /// </returns>
        public override async Task<IdentityResult> SetEmailAsync(User user, string email)
        {
            var dupeUser = await FindByEmailAsync(email);

            if (dupeUser != null)
            {
                return IdentityResult.Failed(new IdentityError() {
                    Code = "DuplicateEmailException", // Wrong practice, lets set some beautiful code values in the future
                    Description = "An existing user with the new email already exists."
                });
            }

            // Perform dupe checks

            // Code that runs in SetEmailAsync
            // Adapted from: aspnet/Identity/blob/dev/src/Core/UserManager.cs
            //
            // ThrowIfDisposed();
            // var store = GetEmailStore();
            // if (user == null)
            // {
            //     throw new ArgumentNullException(nameof(user));
            // }

            // await store.SetEmailAsync(user, email, CancellationToken);
            // await store.SetEmailConfirmedAsync(user, false, CancellationToken);
            // await UpdateSecurityStampInternal(user);

            //return await UpdateUserAsync(user);

            return await base.SetEmailAsync(user, email);
        }

这样,我们保留了.NET Core Identity Code的Integrity,同时强制实现了我们想要的属性/属性的唯一性。

请注意,上面的示例仅适用于现在的电子邮件。只需执行相同操作,然后在UserManager.cs上处理SetPhoneNumberAsync,而不是修改SetEmailAsync。


1
投票

最简单的方法可能就是在控制器中搜索电话号码......

bool IsPhoneAlreadyRegistered = _userManager.Users.Any(item => item.PhoneNumber == model.PhoneNumber);
© www.soinside.com 2019 - 2024. All rights reserved.