I need to return customized validation result (response) invalidation attributes in ASP.Net core Web API This is the ValidationAttribute I have created.
class MaxResultsAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
int maxResults = (int)value;
if (maxResults <= 0)
{
return new CustomValidationResult(new ValidationResult("MaxResults should be greater than 0"));
}
return ValidationResult.Success;
}
}
I have created CustomValidationResult object inheriting ValidationResult so that I can return my own customized response:
public class CustomValidationResult : ValidationResult
{
public int FaultCode { get; set; }
public string FaultMessage { get; set; }
public CustomValidationResult(ValidationResult validationResult) : base(validationResult)
{
FaultCode = 123;
FaultMessage = validationResult.ErrorMessage;
}
}
But it's not working I need to return my own error response
Actual Response:
{
"MaxResults": [
"MaxResults should be greater than 0"
]
}
The response I'm expecting:
{
"code": "55",
"message": "The following validation errors occurred: MaxResults should be greater than 0"
}