I have a controller that expects a list of integers as input like:
[ValidateModel]
[HttpGet("get")]
public IActionResult GetController(int[] ints)
{
// Method body.
}
So, someone can call this route like "http://localhost:8080/get?ints=1,2,3
" and Asp.Net Core automatically parses the string "1,2,3" into an array of integers.
However, the error message returned when say I call this route like "http://localhost:8080/get?ints=foo
" is just the generic error "Invalid model". How can I set my own error message for this?
My ValidateModel
is:
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new ValidationFailureResult(context.ModelState);
}
}
}
And the ValidationFailureResult
is:
public class ValidationFailureResult : ObjectResult
{
public ValidationFailureResult(ModelStateDictionary modelState)
: base(new ValidateModelResult(modelState))
{
this.StatusCode = StatusCodes.Status422UnprocessableEntity;
}
}
public class ValidateModelResult
{
private const string ValidationMessage = "Model state validation failed";
public ValidateModelResult(ModelStateDictionary modelState)
{
this.Message = ValidationMessage;
this.Errors = modelState.Keys
.SelectMany(key => modelState[key].Errors.Select(x =>
new ValidationError(key, x.ErrorMessage)))
.ToList();
}
[JsonConstructor]
private ValidateModelResult(
string message,
List<ValidationError> errors)
{
this.Message = message;
this.Errors = errors;
}
public string Message { get; }
public List<ValidationError> Errors { get; }
}