C# Web API POST parameter FromBody is always null

Devvox93 picture Devvox93 · Aug 9, 2016 · Viewed 10.9k times · Source

I've been scouring the web for hours and tried many different solutions also described here on StackOverflow. I know similar questions have been asked before, but none of the answers or comments have worked for me.

The problem: I have a .NET Web API that has a Post-method with some parameters. One of the parameters is a complex object that is supposed to be read from the body (that is JSON). However, this object is always null.

This is my code:

// POST api/worksheets/post_event/true/false
        [Route("post_event/{newWorksheet}/{eindEvent}")]
        [HttpPost]
        public Event Post(bool newWorksheet, bool eindEvent, [FromBody] Event eventData)
        {
            return eventData;
        }

To be clear: eventData is the object that's always null. The boolean values are read correctly.

The full request body is:

POST http://localhost:5000/api/worksheets/post_event/true/false
Content-Type: application/json
{"Persnr":1011875, "WorksheetId":null, "Projectnr":81445, "Uursoort":8678, "Tijd":{"09-08-2016 9:25"}}

And for reference, this is the Event-class:

public class Event
    {
        public long Persnr { get; set; }
        public int WorksheetId { get; set; }
        public int Projectnr { get; set; }
        public int Uursoort { get; set; }
        public DateTime Tijd { get; set; }
    }

Some of the things I've already tried:

  • Change JSON to different formats (only values, "Event": {} surrounding the actual object, an = in front of the JSON).
  • Test with just the Event parameter (removing the others as well as in the route)
  • Add a default ctor to Event.
  • Remove the [FromBody] tag. If I do this, the Event-object is not null, but all the properties are. Properties can be filled through the URI, but that is not the desired behavior.

According to all solutions and documentation I have read, it should simply work the way I have it displayed above. What am I missing?

Answer

jimmy picture jimmy · Aug 9, 2016

Your json object is invalid. My suggestion is to always run json object written manually through a json parser like this: http://json.parser.online.fr/

"Tijd":{"09-08-2016 9:25"}

should instead be

"Tijd":["09-08-2016 9:25"]