Is there a way I can get an MVC controller to bind incoming dynamic JSON to a JToken object?
If I use an API Controller I can do this:
public class TestController : ApiController
{
public void Post(JToken json)
{
}
}
and the posted json gets converted into a JToken object.
However if I use an MVC controller it results in a server error.
public class TestController : Controller
{
[HttpPost]
public ActionResult TestAction(JToken json)
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
I realise there other ways to obtain the incoming data but I would prefer to receive it as a JToken in the MVC Controller.
I have tried to use a custom ValueProviderFactory from here but I still get a server error returned from my AJAX call:
$.ajax({
url: '/Test/TestAction', //or /api/Test
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({foo:"bar",wibble:"wobble"})
}).done(function (res) {
alert('ok');
}).fail(function (xhr, status, error) {
alert('error')
});
UPDATE:
Note - As stated above I have replaced the default JsonValueProviderFactory with one based on Json.NET.
On further investigation it appears that the problem occurs in the DefaultModelBinder.CreateModel method. When the DefaultModelBinder tries to create a JToken instance it fails because JToken is an abstract class. Even if I change the TestAction parameter to a JObject it stills fails, presumably because there are JToken properties further down the object heirarchy.