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

I have a controller action that accepts a JSON document as the body of a POST request. I would really like to automatically create JObjectfrom this through model binding, for example:

[HttpPost]
public ActionResult Index([FromBody] JObject data)
{
  // "data" is now a populated JObject object
}

But I get errors regarding the creation of an abstract class. I tried to expand something from JObject, but it also will not work.

I know that I can just read the request body and call it JObject.Parse(I do this, so it works), but my idea from above seems a lot more elegant.

Is it possible?

Edit: Actual error:

System.MissingMethodException: Cannot create an abstract class.
[MissingMethodException: Cannot create an abstract class.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
[Stack trace continues...]

The request never gets into the action of the controller.

JObject , , , :

public class Entry : JObject

public ActionResult Index([FromBody] Entry data)

. .

+4
4

, . , , 100%, .

, -

-, ApiController Controller. , .

-, , Content-Type application/json. , . Content-Type , , .

, Application_Start :

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

.

, , . , JSON, JObject , JToken, . , JSON, , JObject.Parse.

+2

JSON . . :

[FromBody] JObject data [FromBody] dynamic data [FromBody] object data

, , .

, , ().

, , POST Content-Type: application/json

0

, - , JObject, `JToken ', . :

. Newtonsoft.Json.Linq.JToken

0

ASP.NET MVC ModelBinder JToken, - https://github.com/mcintyre321/AspNetCoreJTokenModelBinder

JToken, .ToObject<T>()

0
source

Source: https://habr.com/ru/post/1664719/


All Articles