简体   繁体   中英

Sending JSON string to ASP.NET Core MVC Controller

I know how to send simple objects from JavaScript to an ASP.NET Core Controller. But what I'm suppose to do when I have complex a JSON string?

For example I'm using Factory lib. in JavaScript, so when I'm serializing my current Canvas data I'm getting JSON string like this: 在此处输入图片说明

The question is : should I create this complex model in my ASP.NET Core app or is there any other way to get this JSON string in my Controller?

Can I consume a simple json string in my Controller?

It's up to your needs actually.

If you do need a model which provides some methods to process the data, then creating a model could be a good idea.

If you just need to deserialize the JSON string and extract values, you could write your controller like

public ActionResult xxx ([FromBody]dynamic postData)

It will receive the request body as string now.

Be sure to set content-type as application/json in your javascript code

在此处输入图片说明

The original answer looks to use a dynamic object to handle the JSON string.

An alternative approach would be to capture the JSON string into a string.

public IActionResult xxx(string id, [FromBody] string jsonString)

And then de-serialize it.

MyData myData = new JavaScriptSerializer().Deserialize<MyData>(jsonString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM