asp.NET Web API 1 POST endpoint accept JSON parameter always null fix

Every time I need to do accept JSON on a Web API project it drives me nuts, simply because the solution differs each time?! Well, this time I’ve found a solution that should hold it’s weight for any “legacy” projects that may come up in the future where using Web API 2 and asp.NET Core isn’t an option.

The Problem

I have a Complex Type that I wish to receive as a parameter on a POST request made to my server. At this point the reason is unknown, but when debugging the parameter is always null.

The Solution

Make sure you have NewtownSoft.JSON installed in your project. Nowadays you can use the Nuget package manager to accomplish this in Visual Studio.

Make use of the JToken class as your endpoint parameter type, and then perform manual deserialisation by calling YourParameterOfTypeJToken.ToObject<YourType>();  — in the code below you can see “attendanceProxy.ToObject<AttendanceProxy>();” is how I’ve accomplished manual deserialisation.

Below are code samples you may refer to:

The Web API controller

The Complex Type

The JavaScript

 

I hope this helps someone out there! If you have anything to add or a question, please leave a comment below.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.