在Asp.Net Core Identity中要求唯一的电话号码

Sim*_*sen 6 unique asp.net-core asp.net-core-identity

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

有什么办法可以对用户的电话号码执行相同的操作?请注意,我不想要求输入经过确认的电话号码。不需要用户输入电话号码,但是如果输入,则它必须是唯一的。

小智 5

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

bool IsPhoneAlreadyRegistered = _userManager.Users.Any(item => item.PhoneNumber == model.PhoneNumber);
Run Code Online (Sandbox Code Playgroud)


Nic*_*las 3

您可以尝试这个,基本上首先在数据库级别强制执行,然后在管理器级别实施适当的检查。

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

从链接中获取

    // ================== Customizing IdentityCore Tables ================== //

            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);
            });
Run Code Online (Sandbox Code Playgroud)

对于经理级别代码:

    /// <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);
            }
Run Code Online (Sandbox Code Playgroud)

这样,我们可以保留 .NET Core 身份代码的完整性,同时强制我们想要的属性的唯一性。

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