56

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?!

2
  • Change [FromBody] attribute on controller action to [FromForm]
    – Jay Dubal
    Aug 8, 2018 at 10:56
  • Changing to FromForm let the program run, but it didn't transmit the data. Aug 30, 2021 at 14:51

2 Answers 2

77

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

enter image description here

2
  • 4
    Oh man....This is the single most efficient answer i've found till date
    – avg_bloke
    Jun 21, 2019 at 4:48
  • 1
    This is the best answer to this question. It worked. Dec 5, 2019 at 10:41
50

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.

2
  • 2
    Thanks ;) Alternate 1 worked Apr 30, 2017 at 7:39
  • I was using an alternative to Postman called Insomnia, here I had chosen "Form URL Encoded", which gave the content type as specified, but I gave the parameter the name of the c# parameter which did not work, instead I only had to insert the value and no name, that way the request became =value not param=value
    – Peheje
    Dec 17, 2019 at 8:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.