web-api POST body object always null


I'm still learning web API, so pardon me if my question sounds stupid.

I have this in my StudentController:

public HttpResponseMessage PostStudent([FromBody]Models.Student student)
    if (DBManager.createStudent(student) != null)
        return Request.CreateResponse(HttpStatusCode.Created, student);
        return Request.CreateResponse(HttpStatusCode.BadRequest, student);

In order to test if this is working, I'm using Google Chrome's extension "Postman" to construct the HTTP POST request to test it out.

This is my raw POST request:

POST /api/Student HTTP/1.1
Host: localhost:1118
Content-Type: application/json
Cache-Control: no-cache

{"student": [{"name":"John Doe", "age":18, "country":"United States of America"}]}

student is supposed to be an object, but when I debug the application, the API receives the student object but the content is always null.

This question is tagged with c# rest asp.net-web-api

~ Asked on 2014-03-30 08:37:43

The Best Answer is


FromBody is a strange attribute in that the input POST values need to be in a specific format for the parameter to be non-null, when it is not a primitive type. (student here)

  1. Try your request with {"name":"John Doe", "age":18, "country":"United States of America"} as the json.
  2. Remove the [FromBody] attribute and try the solution. It should work for non-primitive types. (student)
  3. With the [FromBody] attribute, the other option is to send the values in =Value format, rather than key=value format. This would mean your key value of student should be an empty string...

There are also other options to write a custom model binder for the student class and attribute the parameter with your custom binder.

~ Answered on 2014-03-30 09:51:27


I was looking for a solution to my problem for some minutes now, so I'll share my solution.

When you have a custom constructor within your model, your model also needs to have an empty/default constructor. Otherwise the model can't be created, obviously. Be careful while refactoring.

~ Answered on 2015-04-20 12:57:45

Most Viewed Questions: