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?
2
Answers
All you need to do is to declare a
JsonConverter
. make sure that your API is usingNewtonsoftJson
for handling api json serialization/deserialization. then you should create a custom JsonConverter which derives fromNewtonsoft.Json.JsonConverter
and handles boolean fields.Then you need to add the convertor that you made to newtonsoftJson
SerializerSettings
in yourProgram.cs
like so: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.
Another possible solution is creating multiple DTOs as [body] inputs on the same endpoint, like so
And your controller would be like this:
After that you can parse the
int
value back tobool
. and the API client can call this endpoint with both int and bool values.BUT if your only concern is the
1/0
andtrue/false
values and not the data Types, you can declare it aspublic string Status {get; set;}
and parse its value tobool
inside your model.