Hello,
How to handle datatype missmatch values in .net core api request object.
Examble :
Have a api request object like below
Class math{
public int number1 {get; set;}
public int number2 {get; set;}
public bool isActive {get; set;}
}
From the request (postman or any other client)
calling the api with below set of request
{
number1 : 20,
number2 : 10,
isActive : "True"
}
The above sample isActive is bool type, but from the request client its like String
Getting the below exception :
The JSON value could not be converted to System.Nullable`1[System.Boolean]'
Thanks in Advance.
Mohamed Azarudeen ZPosted May 11, 2023, 3:07 AM
When handling datatype mismatch values in .NET Core API request objects, you can use data annotations to specify the expected data types for each property in the model class. This can help to ensure that the incoming data is correctly mapped to the correct data type in the model.
In the example you provided, the "isActive" property is defined as a bool, but the incoming value is a string. To handle this scenario, you can modify the model class to include a data annotation that specifies the expected data type for the "isActive" property as shown below:
Class Math
{
public int Number1 { get; set; }
public int Number2 { get; set; }
[DataType(DataType.Boolean)]
public bool IsActive { get; set; }
}
With this modification, the API will now attempt to convert the incoming "isActive" value to a bool type using the specified data type annotation. If the incoming value cannot be converted to the expected data type, the API will throw a validation error, which can be handled by the client application.
In addition to using data annotations, you can also implement custom model binders to handle complex data types or scenarios where the default model binding behavior is not sufficient.