简体   繁体   English

使用ASP.NET Web Api时如何检查电话号码在AspNetUsers表中是否唯一

[英]How to check phone number is unique in AspNetUsers table when using ASP.NET Web Api

I have created an Asp.Net Web Api project and used Individual user accounts. 我创建了一个Asp.Net Web Api项目并使用了个人用户帐户。 When I am adding users to the table the default system automatically checks if the email address supplied already exists in the table, if so a bad request is thrown otherwise the user can be submitted. 当我将用户添加到表中时,默认系统会自动检查表中是否已存在提供的电子邮件地址,如果存在,则会引发错误的请求,否则可以提交用户。

How can I also check if the Phone Number is unique and hasn't already been submitted to the table? 我还如何检查电话号码是否唯一并且尚未提交到表中?

// POST api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            **using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var foundPhoneNumber = await db.Users.FirstOrDefaultAsync(x => x.PhoneNumber.Equals(model.PhoneNumber));

                if (foundPhoneNumber != null)
                {
                    return BadRequest("Phone number already exists");
                }
            }**

            var user = new ApplicationUser()
            {
                UserName = model.Email,
                Email = model.Email,
                PhoneNumber = model.PhoneNumber,
                FirstName = model.FirstName,
                LastName = model.LastName,
                MemberNumber = model.MemberNumber,
                CarReg = model.CarReg
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return GetErrorResult(result);
            }

            return Ok();
        }

I have queried the database to check if there is a Phone Number with the same number. 我已查询数据库以检查是否存在具有相同号码的电话号码。 This works, but is there a better way to do this? 这可行,但是有更好的方法吗?

Modify your ApplicationUser call and add the following attributes. 修改您的ApplicationUser调用并添加以下属性。

public class ApplicationUser : IdentityUser
{
    [MaxLength(17)]
    [IsUnique]
    public string PhoneNumber { get; set; }
}

You can override ValidateEntity method in ApplicationUserDbContext class, it will trigger on SaveChanges method. 您可以在ApplicationUserDbContext类中重写ValidateEntity方法,它将在SaveChanges方法上触发。

protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
        {
            if (entityEntry != null && entityEntry.State == EntityState.Added)
            {
                var errors = new List<DbValidationError>();
                ////User Validation
                if (entityEntry.Entity is ApplicationUser user)
                {
                    if (this.Users.Any(u => string.Equals(u.PhoneNumber, user.PhoneNumber)))
                    {
                        errors.Add(new DbValidationError("User",
                          string.Format($"Phonenumber {user.PhoneNumber} is already taken")));
                    }
                }

                if (errors.Any())
                {
                    return new DbEntityValidationResult(entityEntry, errors);
                }
            }
            return new DbEntityValidationResult(entityEntry, new List<DbValidationError>());
        }

Validation can be added via a custom ValidationAttribute that you add to the PhoneNumber property on you model. 可以通过添加到模型上的PhoneNumber属性的自定义ValidationAttribute来添加验证 Here is a simple example: 这是一个简单的示例:

   [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
   public class NotABananaAttribute : ValidationAttribute
   {
    public override bool IsValid(object value)
    {
        var inputValue = value as string;
        var isValid = true;

        if (!string.IsNullOrEmpty(inputValue))
        {
            isValid = inputValue.ToUpperInvariant() != "BANANA";
        }

        return isValid;
    }
   }

And its used liked this... 它使用喜欢...

public class Model
{
    [NotABanana(ErrorMessage = "Bananas are not allowed.")]
    public string FavoriteFruit { get; set; }
}

Example sourced from: https://riptutorial.com/csharp/example/18486/creating-a-custom-validation-attribute 示例来源: https//riptutorial.com/csharp/example/18486/creating-a-custom-validation-attribute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取ASP.Net MVC 5中AspNetUsers表中的ApplicationUser数量? - How to get the Number of ApplicationUser in the AspNetUsers Table in ASP.Net MVC 5? ASP.NET MVC-将Identity与现有的经过修改的AspNetUsers表一起使用 - ASP.NET MVC - Using Identity with existing, modified AspNetUsers table Asp.net核心 - 没有这样的表:AspNetUsers - Asp.net core - no such table: AspNetUsers 使用asp.net web api检查上传的文件是否为图像 - Check uploaded file is a image or not using asp.net web api 是否将用户设置存储在ASP.NET Core身份AspNetUsers表中 - Store User Settings in ASP.NET Core Identity AspNetUsers Table or Not 使用ASP.Net Identity EntityFramwork到ID列设置为UniqueIdentifier的现有AspNetUsers表 - Using ASP.Net Identity EntityFramwork to Existing AspNetUsers table with ID Column set to UniqueIdentifier ASP.NET Identity 从 AspNetUsers 表中删除列 - ASP.NET Identity remove column from AspNetUsers table ASP.NET Core MVC 唯一电话号码和 SSN - ASP.NET Core MVC Unique Phone Number and SSN 如何有条件地将 map 多个模型添加到 ASP.NET 核心标识中的一张表(AspNetUsers)? - How to conditionally map multiple models to one table (AspNetUsers) in ASP.NET Core Identity? 健康检查,ASP.NET Web API - Health check, ASP.NET Web API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM