0

I am on Dotnet 3.0.103. I have exposed a webapi, that has a code defined like this,

[HttpPost]
        public string Post([FromBody] string data)
        {
            try
            {
            EmployeeRequest request = JsonConvert.DeserializeObject<EmployeeRequest>(data);

Now, when I call the API from my postman, a normal json request body like this, does not work

{"EmployeeId": 3, "Name": "John"}

It throws an error like this,

{
    "errors": {
        "": [
            "Unexpected character encountered while parsing value: {. Path '', line 1, position 1."
        ]
    },
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|b9ea70ff-4ffda7ef1c244839."
}

Where as an escaped string as opposed to a Json body works fine,

 "{\"EmployeeId\": 3, \"Name\": \"John\"}"

I would like to make it work with just a plain json.

Any help is appreciated.

Thanks, Arun

Arun A Nayagam
  • 195
  • 2
  • 9
  • Just out of curiosity try changing your data variable to an object type [FromBody] object data . Then convert it to a string. – Patrick Mcvay Apr 02 '20 at 12:53
  • 3
    You'll be better putting the model in to the Action's parameters and letting ASP.Net's model binding take care of the deserialization for you - `public string Post([FromBody]EmployeeRequest request)`. – phuzi Apr 02 '20 at 12:55
  • Sorry I am extremely new to Dotnet. Should I cast it like this, `[HttpPost] public string Post([FromBody] object data) { try { EmployeeRequest request = JsonConvert.DeserializeObject((string)data);` When I do this, I get this error `System.InvalidCastException: Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'System.String'` – Arun A Nayagam Apr 02 '20 at 12:56
  • 1
    I agree with @phuzi – Patrick Mcvay Apr 02 '20 at 12:58
  • But its not allowing me to cast the body as a string, cannot convert from `'EmployeeApi.EmployeeRequest' to 'string'` This `JsonConvert.DeserializeObject` seems to expect a string – Arun A Nayagam Apr 02 '20 at 13:02

2 Answers2

1

ASP.Net's model binding can bind a JSON payload to your Action's parameters automatically. As such you should be able to do away with the manual deserialization:

[HttpPost]
public string Post([FromBody]EmployeeRequest request)
{
    // request should be properly populated
phuzi
  • 12,078
  • 3
  • 26
  • 50
0

You don't need to separately deserialize the json. .NET can do that for you out of the box. Try changing the signature to: public string Post([FromBody] EmployeeRequest data)and make the call from postman without escaping. It should work.