Tomas Sundvall
Tomas Sundvall

Reputation: 54

How do I get model binding not to stop after first failure

I am trying to implement well described errors in my WebApi if a request fails. When trying to bind a json body to a DTO class I get very nice readable errors for the first property where the model binding fails, but then it seems to stop. I want to return back information of all the fields where model binding failed.

My DTO class looks like the following:

public class RequestDTO
{
   public int FirstValue { get; set; }
   public int SecondValue { get; set; }
}

When passing in the following JSON

{
    "firstValue": "y",
    "secondValue": "x"
}

I get the following response

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|6ba7ef4a-442494fd16304f12.",
    "errors": {
        "$.firstValue": [
            "The JSON value could not be converted to System.Int32. Path: $.firstValue | LineNumber: 1 | BytePositionInLine: 18."
        ]
    }
}

What I am trying to achieve is to get a response like

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|6ba7ef4a-442494fd16304f12.",
    "errors": {
        "$.firstValue": [
            "The JSON value could not be converted to System.Int32. Path: $.firstValue | LineNumber: 1 | BytePositionInLine: 18."
        ],
        "$.secondValue": [
            "The JSON value could not be converted to System.Int32. Path: $.secondValue | LineNumber: 1 | BytePositionInLine: 19."
        ]
    }
}

But I just can't figure out how to do that. I hope that my question was clear enough, otherwise please post a comment and I will update.

Upvotes: 0

Views: 306

Answers (1)

Piotr L
Piotr L

Reputation: 989

Since version 3.0 ASP.NET Core uses System.Text.Json for handling JSON. It stops deserialization on the first error and there doesn't seem to be a setting for disabling it.

If you need more deserialization errors you can use old Newtosoft.Json. Just add Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget package and add change the following line in ConfigureServices

services.AddControllers();

to

services.AddControllers().AddNewtonsoftJson();

However, System.Text.Json has got better perforamnce and it's reccomended to use it.

Upvotes: 1

Related Questions