Click here to Skip to main content
15,069,020 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a situation, One of my API which was in .net WebAPI have converted to .NetCore API. The data flow architecture
is same for both i.e Controller is defined, Request comes through JSON & is binded to Model with all parameters in model
as string.

The issue here is for my old API ( Asp.net Web API) , one of my parameter MobileNo if I pass it in string or integer it accepts it
& process the flow further.

But in (.Net Core API ) it does not happens this way. If I pass Mobile no. in string it accepts the request.
but if numeric value is passed i get null object in Model.

Have provided below sample request which is accepted
& the one which is passed as null

Accepted request
{
"EmployeeCode":"1234"
"EmployeeName":"Test"
"MobileNo":"1234567890"
}


Null Model Passed for
{
"EmployeeCode":"1234"
"EmployeeName":"Test"
"MobileNo":1234567890
}



My model and controller code is below
 public class EmpRequest 
    { 
        public string EmployeeCode { get; set; } 
        public string EmployeeName { get; set; }
        public string MobileNo { get; set; }
}


[HttpPost]
        [ProducesResponseType(200)]
        [ProducesResponseType(500)]
        public async Task<IActionResult>APIGetEmployee([FromBody] EmpRequest reqModel)
        {
}


What I have tried:

I have tried to convert the value in controller
Convert.Tostring(reqModel.MobileNo )
but its not work as model itself coming is null in request.
Posted
Updated 9-Aug-21 21:38pm
v2

1 solution

This is due to .NET Core using the new System.Text.Json library instead of the Newtonsoft.Json library.

You should be able to register a custom converter to allow it to read a string property from a number, as shown in this SO thread:
c# - System.Text.Json: Deserialize JSON with automatic casting - Stack Overflow[^]

However, passing a telephone "number" as a number is a mistake. Despite the name, it's not a "number" in that sense. For example, you cannot add two telephone numbers together, or subtract them from each other, or multiply them together, etc.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900