55

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

Saeed Ahmadian
  • 1,112
  • 1
  • 10
  • 21

2 Answers2

75

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

enter image description here

Feiyu Zhou
  • 4,344
  • 32
  • 36
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.

Igor
  • 60,821
  • 10
  • 100
  • 175
  • 2
    Thanks ;) Alternate 1 worked – Saeed Ahmadian Apr 30 '17 at 07: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 '19 at 08:11