0

我正在使用 ASP.NET Core 5,.NET 5 版本5.0.100-rc.1.20452.10。我有一个模型需要验证

/// <summary>
/// Model của form dùng khi admin thêm mới người dùng từ giao diện quản trị.
/// </summary>
public class AddUserForm
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    public string Password { get; set; }        
        
    public string About { get; set; }

    public string Fullname { get; set; }
    public string AliasName { get; set; }
    public string SecondMobile { get; set; }
    public string PhoneNumber { get; set; }

    [DataType(DataType.Upload)]
    public IFormFile file { get; set; }
}

验证规则必须具有(必需)2 个字段中的 1 个:AboutAliasName。它的意思是

  1. About,没有AliasName,没关系。

  2. About,有AliasName,没关系。

  3. About,有AliasName,没关系。

  4. About,不AliasName,这样不行。

控制器

/// <summary>
/// Admin Thêm mới người dùng từ giao diện quản trị.
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
[HttpPost]
public async Task<ActionResult<string>> AddUser([FromForm] AddUserForm form)
{
    if (ModelState.IsValid)
    {
        ApplicationUser user = new ApplicationUser();
        // https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.createasync?view=aspnetcore-3.1
        // user.PasswordHash = HashPassword()
        if (String.IsNullOrEmpty(form.Email))
        {
            user.Email = form.Email;
        }
        user.EmailConfirmed = true;

        if (String.IsNullOrEmpty(form.Email))
        {
            user.NormalizedEmail = form.Email.ToUpper();
        }
        if (String.IsNullOrEmpty(form.About))
        {
            user.About = form.About;
        }
        if (String.IsNullOrEmpty(form.AliasName))
        {
            user.AliasName = form.AliasName;
        }
        if (String.IsNullOrEmpty(form.Fullname))
        {
            user.Fullname = form.Fullname;
        }
        if (String.IsNullOrEmpty(form.PhoneNumber))
        {
            user.PhoneNumber = form.PhoneNumber;
        }
        if (String.IsNullOrEmpty(form.SecondMobile))
        {
            user.SecondMobile = form.SecondMobile;
        }
        if (String.IsNullOrEmpty(form.Email))
        {
            user.UserName = form.Email;
        }
        //FIXME: Chưa có phần thêm avatar.
        if (form.file != null)
        {
            // Ghi file. Làm tương tự khi thêm Asset.
            if (IsImageFile(form.file))
            {
                string imgPath = await WriteFile(form.file);
                user.Avatar = imgPath;
            }
            else
            {
                return BadRequest(new { message = "Invalid file extension" });
            }
        }
        string pass = form.Password;
        user.Created = DateTime.Now;
        user.Modified = DateTime.Now;
        await _userManger.CreateAsync(user, pass);
        await _db.SaveChangesAsync();
        return Ok(user);
    }
    else
    {
        return BadRequest(ModelState);
    }            
}

如何实现这个验证规则,我更喜欢使用注解。

4

1 回答 1

1

尝试使用以下代码创建自定义验证方法:

public class AddUserForm
    {
        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        public string Password { get; set; }

        public string About { get; set; }

        public string Fullname { get; set; }

        [RequiredIfHasValue("About", ErrorMessage ="About or AliasName is Required")]
        public string AliasName { get; set; }
        public string SecondMobile { get; set; }
        public string PhoneNumber { get; set; }
    }

    public class RequiredIfHasValueAttribute : ValidationAttribute
    {
        private readonly string _comparisonProperty;

        public RequiredIfHasValueAttribute(string comparisonProperty)
        {
            _comparisonProperty = comparisonProperty;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ErrorMessage = ErrorMessageString;

            //get entered alias name
            var aliasName = (string)value;
            var property = validationContext.ObjectType.GetProperty(_comparisonProperty);
            if (property == null)
                throw new ArgumentException("Property with this name not found");
            //get the about value
            var aboutValue = (string)property.GetValue(validationContext.ObjectInstance);

            if (aliasName == null && aboutValue == null)
                return new ValidationResult(ErrorMessage);
             
            return ValidationResult.Success;
        }
    }
 
于 2020-09-18T07:22:54.537 回答