Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Catch Json Deserialization Error In Middleware

I'm certain I'm missing something patently obvious.

Is it possible to handle JSON deserialization errors in .NET Core's default middleware/deserializer? I need to be sure that a particular value is a JSON primitive and not an object/array. If it's not a primitive, I'd like to terminate the request and return the appropriate status code before it gets to the controller.

Controller:

[HttpPost]
public IActionResult Post([FromBody] List<MyType> myTypes)
{
    // Logic ....

    return Created(new Uri("some-location/", UriKind.Relative), someValue);
}

Request body:

[
    {
        "prop1": "some value",
        "prop2": "some value",
        "prop3": null
    },
    {
        "prop1": "some value",
        "prop2": "some value",
        "prop3": {
            "prop3-1": "some value"
        }
    }
]

The MyType constructor inspects the arguments passed in and throws an exception if there's a problem. prop3 in MyType is a dynamic field. I've verified that the exception is being thrown when the second item in the request body is deserialized.

This all feels pretty straightforward but I just can't find where to access the default deserializer.

I tried this and it does catch errors but only after the request has made it into the controller.

Is there a way to handle this in JSON annotations? I looked through the Newtonsoft docs but nothing jumped out.

like image 296
user2864874 Avatar asked Jun 02 '26 15:06

user2864874


1 Answers

Looking at the documentation here: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.1 I think what you are looking for is the AddJsonOptions()

in Startup.cs:

services.AddMvc().AddJsonOptions(options =>
{
     options.SerializerSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Error;
});

This will not throw an exception, but it will fail to bind, so myTypes becomes null.

Then you can just add a null check

[HttpPost]
public IActionResult Post([FromBody] List<MyType> myTypes)
{
    if(myTypes == null)
    {
        return BadRequest();
    }

    // Logic ....

    return Created(new Uri("some-location/", UriKind.Relative), someValue);
}
like image 145
Marcel Avatar answered Jun 05 '26 23:06

Marcel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!