Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Web API POST parameter FromBody is always null

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?

like image 878
Devvox93 Avatar asked Aug 24 '26 21:08

Devvox93


2 Answers

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"]
like image 127
jimmy Avatar answered Aug 26 '26 12:08

jimmy


This usually happens when your object can't be deserialized from JSON request.

The best practice would be to make sure that all the request properties can accept null values (make value types properties are nullable). And then you can validate that all needed request properties are provided, or return 400 error if not. This way you at least will be able to understand what request property causes the problem.

like image 35
Dmitry Pavlov Avatar answered Aug 26 '26 13:08

Dmitry Pavlov