I've decorated a POCO with .net core data annotations.

public class Foo
{
    [Required]
    [StringLength(100, MinimumLength = 1)]
    public String Name { get;set;}
}

When I call the API controller with invalid data these data validation rules are kicking in returning an HTTP 400. The payload looks something along the lines of:

{
    "name": [
        "The Name field is required."
      ]
}

My two questions:

  1. I've seen quite a few docs referring to ModeState.IsValid, in my case the controllers are not even being entered and neither are any custom action filters ive added.

  2. Is it possible however to control/configure the payload response?

I would like to return more of a structured response

{
    "reason":"Invalid request",
    "errorCode":"BadFooDetails",
    "data" : {
       "name": [
           "The Name field is required." ]
           } 
}

The main reason for doing this is to have a consistent structured ApiError response payload.

1 Answers

-1
Francesco D.M. On

If I understand this correctly you are looking for the ErrorMessage attribute of the data annotations.

In your case it should look something like

[Required(ErrorMessage = "My custom error message")]
[StringLength(100, MinimumLength = 1)]
public string Name { get; set; }

Another option (which I suggest) would be to use the FluentValidation library. Very very flexible.