Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post received by FromBody causes serializable error

Here's the basic setup, I have an asp.net core webapi controller (in c#) with a post function like so:

[HttpPost]
public ActionResult<string> Post([FromBody] string Name)
{
     //Do some processing with the "Name" argument...
     return Ok( "Success!" );
}

I'm trying to send the following raw JSON request body to this function:

{
    "Name": "Foo"
}

But when send a post request to this function with the body above, I get back the following error in the server console:

"Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.SerializableError'"

And this error on the client side

{ "": [ "Unexpected character encountered while parsing value: {. Path '', line 1, position 1." ] }

I tried setting a break point at the beginning of the function but it doesn't even trigger! Why am I getting a serializable error?

like image 647
Vance Palacio Avatar asked Aug 29 '18 04:08

Vance Palacio


2 Answers

The serializable error is actually a parsing error from JSON.NET, but the problem actually has nothing to do with parsing JSON.

The real issue is that ASP.NET Core expects to parse a JSON body into an object/DTO. So you have two options you can use to fix the problem:

  1. Make a simple DTO container object for your single parameter e.g.:

    public class SimpleObject { 
        public string Name { get; set; } 
    }
    
  2. Instead of passing a full fledged JSON object in your request body, just use a simple string e.g: "My parameter string"

like image 147
Vance Palacio Avatar answered Nov 03 '22 23:11

Vance Palacio


You need a body in which json data will be parsed.

[FromBody] string Name

can not work with following json

{
    "Name": "Foo"
}

It needs a class

public class MyClass 
{ 
    public string Name;
}

Then pass it as

([FromBody] MyClass obj)

Or if it is single value, use JSON like

{
    [
       "Foo",
       "Foo1"
    ]
}

Then pass it as

([FromBody] List<string> obj)
like image 30
ManishM Avatar answered Nov 04 '22 01:11

ManishM