2

I have the setup a test command line app using self hosting OWIN. I have one test controller and this works as expected to deliver a static home page plus two values in JSON format on a get request.

I'm using the JsonFormatter to format all results.

I would like to read JSON data into it from a post request. I can send an accepted message response but the data is always null when read.

// POST api/values 
[HttpPost]
public HttpResponseMessage Post([FromBody]string myString)
    {
        Console.WriteLine("Terry Tibbs");
        Console.WriteLine(myString);
        return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
    }

I'm using Postman in Chrome to post data as below but myString is always blank.

POST /api/values HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: a966fa36-010d-3e2b-ad66-2f82dcb155ed
{
   "myString": "This is new"
}
Matthew
  • 497
  • 1
  • 5
  • 16

1 Answers1

1

Read Parameter Binding in ASP.NET Web API

Using [FromBody]

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter:

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

In this example, Web API will use a media-type formatter to read the value of myString from the request body. Here is an example client request.

POST api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:8080
Content-Type: application/json
Content-Length: 13

"This is new"

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).

Nkosi
  • 235,767
  • 35
  • 427
  • 472