In ASP.NET MVC, can I automatically model bind to a JObject from the POST body? In ASP.NET MVC, can I automatically model bind to a JObject from the POST body? json json

In ASP.NET MVC, can I automatically model bind to a JObject from the POST body?


You should also put the structure of the JSON in your question. The full request would be better. Until then, try the following:

replace [FromBody] JObject data with [FromBody] dynamic data or [FromBody] object data

and see if it hits a breakpoint put on the first line of the action.

If it does, see what your dynamic actually is (type).

If it does not, maybe the POST request does not have Content-Type: application/json


There might have been two problems. I changed two things, and it works now, but I'm not 100% sure which one fixed it.

Here are both things I changed --

First, I inherited from ApiController instead of just Controller. I'm not sure if this had anything to do with it.

Second, one of the other answers pointed out that I needed to have the correct Content-Type header of application/json. Well, it wasn't. The Content-Type header was set to some wild value specific to the software we're integrating with.

So, in Application_Start, I added this:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("[crazy ass content-type header value]"));

And then it worked.

I suspect it was the second thing that fixed it. Since the header didn't tell the model binder it was incoming JSON, the binder was trying to create a JObject object from scratch and assign properties via reflection which ran into problems with JToken being abstract. Once it knew it was dealing with JSON, it knew to just call JObject.Parse instead.


I've written a ASP.NET Core ModelBinder for JToken which you can install - https://github.com/mcintyre321/AspNetCoreJTokenModelBinder

Bind to JToken, then use .ToObject<T>() in your controller