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"
}
I have reproduced the problem using your code, using the CustomValidationResult, I could only get the Actual Response like yours. To achieve above behavior, as a workaround, I suggest you could try to use the action filter to handle the Validation failure error response. Check the following sample code:
Create custom ValidationError model which contains the returned fields:
Create custom IActionResult. By default, when display the validation error, it will return BadRequestObjectResult and the HTTP status code is 400. Here we could change the Http Status code.
Create Custom Action Filter attribute:
Change the default response type to SerializableError in Startup.ConfigureServices:
Add the custom action filter at the action method or controller.
Create a Student model with custom attribute validation (Min18Years):
After running the application, the result like this:
Reference:
Handle Validation failure errors in ASP.NET Core web APIs
Handling validation responses for ASP.NET Core Web API