Web API attribute validation does not return all errors

382 Views Asked by At

I have an ASP.NET Core 6 Web API project with all controllers decorated with the [ApiController] annotation. I use validation annotations like [Required], [MaxLength] etc. to validate properties of DTOs received in incoming requests.

Some of my DTOs also implement the IValidatableObject interface, to handle more complex validation scenarios not covered by the attributes.

When DTO in the request is invalid because IValidatableObject.Validate() returned some ValidationResults, the corresponding validation error messages appear in the response.

But when the DTO ALSO has validation errors because of the attributes, only attribute-related error messages appear in the response.

How can I get all errors to appear?

Here's another, more complex scenario, when not all errors appear in the response. Let's say I have two DTOs - Parent and Child. Parent has property Children of type ICollection<Child>. Child has some validation attributes on its properties. Parent has a validation attribute on the Children property that checks that the property value, which is a collection, does not contain nulls.

If in the request I send a Parent with Children collection containing two items - an invalid Child and a null, the response has only one error message, the one about the invalid child. If I make the child valid, then the message about null in the Children collection starts coming up.

1

There are 1 best solutions below

2
Xinran Shen On

If you want to show error message together, You can custom validation attribute with ValidationAttribute instead of implement IValidatableObject, Here is a simple demo:

public class CountAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            
            int Count = (int)value;

            if (Count > 3 && Count < 7)
            {
                return new ValidationResult("Count is not valid, Please try again");
            }
            return ValidationResult.Success;
        }
    }

Model

public class Parent 
    {
        [Range(1,5)]
        public int MaxCount { get; set; }

        [Count]
        public int Count { get; set; }
       
    }

Now if the request model is invalid, It will response all the error message.

enter image description here