Search code examples
jsonrest.net-coredeserializationminimal-apis

How to configure JSON deserialization options in .NET minimal API project


I have a .NET minimal API project, as described here. One of the endpoints accepts JSON in the request body, and this is deserialized automatically. The code looks something like this:

app.MapPost("/myendpoint", async (MyInputFromBody input) => { ... });

This works in general, but I would like to specify options for deserialization. For instance, the JSON has some date fields such as "myDate": "2021-04-01T06:00:00", which can be converted to a DateTime, but an empty date value "myDate": "" throws an exception (System.FormatException: The JSON value is not in a supported DateTime format.).

I found a suggestion to write my own DateTime converter and use this:

builder.Services.AddControllers()
    .AddJsonOptions(options => options.JsonSerializerOptions.Converters.Add(new JsonDateTimeConverter()));

but this doesn't seem to do anything. A breakpoint in my converter is never hit, and I get the same exception as before.

Is there a way to specify JSON options, or should I use a string parameter, as in [FromBody] string body, and parse that myself?


Solution

  • AddControllers().AddJsonOptions is configuring for your controllers, To configure for Minimal api all you have to do is:

    builder.Services.Configure<JsonOptions>(options => options.SerializerOptions.Converters.Add(new JsonDateTimeConverter()));
    

    Tutorial on this

    ASP.NET Core supports two approaches to creating APIs: a controller-based approach and minimal APIs. Controllers in an API project are classes that derive from ControllerBase. Minimal APIs define endpoints with logical handlers in lambdas or methods. This article points out differences between the two approaches.

    Difference