Null value when Pass values [FromBody] to post method by Postman plugin

C#asp.net Web-ApiPostman

C# Problem Overview


I use api controller in ASP.net web API and i need to pass value to post method by [FromBody] type..

 [HttpPost]
 public HttpResponseMessage Post( [FromBody]string name)
 {
     ....
 }

i use Postman plugin but when send to post method value of name always is null.. follow this image: enter image description here

and in Post methods : enter image description here

why this happend?!

C# Solutions


Solution 1 - C#

Post the string with raw json, and do not forget the double quotation marks.

enter image description here

Solution 2 - C#

You can't bind a single primitive string using json and FromBody, json will transmit an object and the controller will expect an complex object (model) in turn. If you want to only send a single string then use url encoding.

On your header set

Content-Type: application/x-www-form-urlencoded

The body of the POST request message body should be =saeed (based on your test value) and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.


Alternate 1

Create a model and use that instead.

Message body value: {"name":"saeee"}

c#

public class CustomModel {
	public string Name {get;set;}
}

Controller Method

public HttpResponseMessage Post([FromBody]CustomModel model)

Alternate 2

Pass primitive strings to your post using the URI instead of the message body.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaeed Ahmadian MasalView Question on Stackoverflow
Solution 1 - C#Feiyu ZhouView Answer on Stackoverflow
Solution 2 - C#IgorView Answer on Stackoverflow