ModelState validation, only shows one error at a time

158 views Asked by At

I have a WebAPI decorated with [ApiController] and have been testing the validation of the models. I noticed that they only return one validation error at a time, but in an array format. I purposely created several errors because I wanted to see the full report. So far all I have seen are a few questions with the same behaviour, but no answers.

Sample model:

public class MyModel {
    [Range(0,12)]
    public int MyInt { get; set; }
    public DateTime MyDate { get; set; }
}

Sample JSON:

[
    {
        "MyInt": "textinanint",
        "MyDate": "2020-09-29 5:00 PM"
    }
]

Please note that date is not a valid JSON encoded date. There are two errors, but the validator will only return the first one like so:


{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|5fb75d1b-454a15260c502256.",
  "errors": {
    "$[0].myInt": [
      "The JSON value could not be converted to System.Int32. Path: $[1].myInt| LineNumber: 2 | BytePositionInLine: 30."
    ]
  }
}

I would except to see:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|5fb75d1b-454a15260c502256.",
    "errors": {
        "$[0].myInt": [
            "The JSON value could not be converted to System.Int32. Path: $[0].myInt| LineNumber: 3 | BytePositionInLine: 30."
        ],
        "$[0].myDate": [
            "The JSON value could not be converted to System.DateTime. Path: $[0].myDate| LineNumber: 2 | BytePositionInLine: 22."
        ]
    }
}

Is there a way to correct this behaviour? Forgive any issues with the json formatting in the expected output. I had to create it manually.

0

There are 0 answers