string value is Empty when using FromBody in asp.net web api

I am using asp.net core web api. below is my simple post function which is having a single string parameter. The problem is when I use [FromBody] the string stays null. I am using PostMan to test my service. I want raw data to pass from client to my controller. In Postman I am selecting body type RAW and
I set the header Content-Type text/plain. The Raw Body contains Just “Hello World” string.

[HttpPost]
        [Route("hosted-services/tokenize-card")]
        public IActionResult Test([FromRoute]decimal businessKey,[FromBody] string body)
        {
            var data = businessKey;
            return new JsonResult("Hello World");
        }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Like the doc says :

When a parameter has [FromBody], Web API uses the Content-Type header
to select a formatter.

Only XML and JSON content-types are supported by default. So you need to use application/xml, application/json or register a custom IInputFormatter.

Next, you need to send a content that match the selected content-type.
For json, if the parameter is int send a number. If it’s a class, send a json object. If it’s a string, send a json string. Etc.

int => 14
string => "azerty"
class => { "propName" : "value" }
Array => []
... => ...

In your case you should send application/json content-type and as content :
"Hello string"

And not just
Hello string

Aspnet core json input formatter implementation

Aspnet core xml input formatter implementation

Example: Creating a CSV Media Formatter

Method 2

I did make it work by passing as row data in PostMan. Do not forget to add “=”
sign as prefix in to the values.

 public string Post([FromBody]string value)
 {
     return value;
 }

enter image description here

Method 3

Frombody means that get body directly.it is not necessary to use variable and value pairs.

For Example:

Your controller is like this.

[HttpPost]
public IActionResult GetStringFromBody([FromBody] string token)
    {
    ...
    }

False:

string value is Empty when using FromBody in asp.net web api

True:

string value is Empty when using FromBody in asp.net web api


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x