1

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; }
}
kovac
  • 4,945
  • 9
  • 47
  • 90
  • I had a similar requirement for an MVC 5 application (require floats to use decimal point only). We solved it by writing custom `ModelValidatorProvider` and `ModelValidator` and registered them in Global.asax with `ModelValidatorProviders.Providers.Add(new CustomModelValidatorProvider());`. This solution followed the tutorial at [Custom Server and Client Side Required Validator in MVC 2 using jQuery.validate](http://jwwishart.blogspot.com/2011/03/custom-server-and-client-side-required.html). I dont know if this is still applicable for .net-core. – Georg Patscheider Sep 18 '19 at 08:19
  • What is your own error message ? Could you share more details about the screenshot of the expected result and the actual result that you get ? – Xueli Chen Sep 18 '19 at 10:01
  • Does this answer your question? [How do I customize ASP.Net Core model binding errors?](https://stackoverflow.com/questions/51145243/how-do-i-customize-asp-net-core-model-binding-errors) – Ian Kemp Aug 24 '20 at 13:03

0 Answers0