简体   繁体   English

将 JSON 字符串发送到 ASP.NET Core MVC 控制器

[英]Sending JSON string to ASP.NET Core MVC Controller

I know how to send simple objects from JavaScript to an ASP.NET Core Controller.我知道如何将简单对象从 JavaScript 发送到 ASP.NET Core 控制器。 But what I'm suppose to do when I have complex a JSON string?但是当我有一个复杂的 JSON 字符串时,我应该怎么做?

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:在 JavaScript 中,所以当我序列化我当前的 Canvas 数据时,我得到这样的 JSON 字符串: 在此处输入图片说明

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?问题是:我应该在我的 ASP.NET Core 应用程序中创建这个复杂的模型,还是有其他方法可以在我的控制器中获取这个 JSON 字符串?

Can I consume a simple json string in my Controller?我可以在我的控制器中使用一个简单的 json 字符串吗?

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如果您只需要反序列化 JSON 字符串并提取值,您可以像这样编写控制器

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确保在你的 javascript 代码中将 content-type 设置为 application/json

在此处输入图片说明

The original answer looks to use a dynamic object to handle the JSON string.原始答案看起来使用动态对象来处理 JSON 字符串。

An alternative approach would be to capture the JSON string into a string.另一种方法是将 JSON 字符串捕获为字符串。

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

And then de-serialize it.然后反序列化它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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