Manually validate Model in Web api controller

前端 未结 4 405
梦毁少年i
梦毁少年i 2020-12-31 20:24

I have a class called \'User\' and a property \'Name\'

public class User
{
    [Required]
    public string Name { get; set; }
}

And api co

相关标签:
4条回答
  • 2020-12-31 21:02

    You will need to define custom Validation Attribute as

    class CustomValidatorAttribute : ValidationAttribute
    {
      //custom message in ctor
      public CustomValidator() : base("My custom message") {}
      public CustomValidator(string Message) : base(Message) {}
      public override bool IsValid(object value)
      {
         return !string.IsNullOrWhiteSpace(value.ToString());
      }
      //return a overriden ValidationResult
      protected override ValidationResult IsValid(Object value,ValidationContext validationContext)
      {
         if (IsValid(value)) return ValidationResult.Success;
         var message = "ohoh";
         return new ValidationResult(message);
      }
     }
    

    likewise in your model class

    public class User
    {
      [Required]
      [CustomValidator("error")]
      public string Name { get; set; }
    }
    
    0 讨论(0)
  • 2020-12-31 21:06

    You can use the Validate() method of the ApiController class to manually validate the model and set the ModelState.

    public IHttpActionResult PostUser()
    {
        User u = new User();
        u.Name = null;
    
        this.Validate(u);
    
        if (!ModelState.IsValid)
            return BadRequest(ModelState);
    
        return Ok(u);
    }
    
    0 讨论(0)
  • 2020-12-31 21:09

    This answer is not for this case, but it is very relevant if you want to validate a parameter manually:

    public IHttpActionResult Post(User user)
    {
        ModelState.Clear(); // remove validation of 'user'
                            // validation is done automatically when the action
                            // starts the execution
    
        // apply some modifications ...
    
        Validate(user); // it adds new keys to 'ModelState', it does not update any keys
    
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
    
        // ...
    }
    
    0 讨论(0)
  • 2020-12-31 21:21

    The model should be an input parameter to your ActionMethod, and ModelState.IsValid will validate as per the attributes you set in the Model class, in this case as it is set [Required] it will be validated againg null values,

    and if you just wish to manually check whether there is a value, you can check it directly.

    if (user.Name == null) {
      return;
    }
    
    0 讨论(0)
提交回复
热议问题