Search code examples
c#asp.netasp.net-coremodel-bindingapi-design

How to handle both 0/1 and false/true values for booleans in requestbody


I'm currently migrating functionalities from an old HTTP API to a new HTTP API. Several endpoints of the api expect objects with nullable boolean values as a JSON object in the requestbody.

Modelcode:

public class StatusRequest
{
    public bool? Status {get; set;}
}

Controller:

[HttpPost, Route("")]
public async Task<IActionResult> RequestStatus([FromBody] StatusRequest requestData )
{
    if(requestData.Status)
    {
        return Ok();
    }
    else
    { 
        return BadRequest(); 
    }
}

My problem is now that since I'm migrating from an old API that used 0/1 integers as boolean values and we want the neccessary changes on the userside to be as minimal as possible, the API should be able to read both 0/1 and false/true for the properties in the requestbody.

First I tried to implement a custom model binding class implementing IModelBinder, that handles the 0/1 and the nullable values but the binding was ignored due to the [FromBody] attribute. I can't remove the [FromBody] attribute though, because then our swagger documentation displays the requestmodel as individual parameters and not as a single requestbody. I also can't add examples of requestbodies to the documentation because the OpenApiOperation class doesn't have a RequestBody property anymore.

Is there a way I can handle my nullable and integer values and still have a correct documentation?


Solution

  • All you need to do is to declare a JsonConverter. make sure that your API is using NewtonsoftJson for handling api json serialization/deserialization. then you should create a custom JsonConverter which derives from Newtonsoft.Json.JsonConverter and handles boolean fields.

    Then you need to add the convertor that you made to newtonsoftJson SerializerSettings in your Program.cs like so:

    builder.Services.AddControllers()
        .AddNewtonsoftJson(options => {
            options.SerializerSettings.Converters.Add(new BoolJsonConverter());
        });
    

    If you want to know how you can declare a BoolJsonConverter you can take a look at How do I get Newtonsoft to serialize a bool as false, not False or "false".

    Let us know if it could help you solve your problem.