将动态 JSON 对象传递给 Web API - Newtonsoft 示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14071715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:41:06  来源:igfitidea点击:

Passing Dynamic JSON Object to Web API - Newtonsoft Example

asp.net-mvcjsonasp.net-mvc-4asp.net-web-api

提问by davy

I need to pass a dynamic JSON object to my Web API controller so that I can process it depending on what type it is. I have tried using the JSON.NET example that can be seen herebut when I use Fiddler, I can see that the passed in JObect is always null.

我需要将动态 JSON 对象传递给我的 Web API 控制器,以便我可以根据它的类型来处理它。我尝试使用可以在此处看到的 JSON.NET 示例但是当我使用 Fiddler 时,我可以看到传入的 JObect 始终为空。

This is an exert from the example pasted into Fiddler:

这是粘贴到 Fiddler 的示例中的一个应用:

POST http://localhost:9185/api/Auto/PostSavePage/  HTTP/1.1
User-Agent: Fiddler
Content-type: application/json
Host: localhost
Content-Length: 88

{AlbumName: "Dirty Deeds",Songs:[ { SongName: "Problem Child"},{ SongName:  
"Squealer"}]}

Ans here is my very simple Web API controller method:

这是我非常简单的 Web API 控制器方法:

 [HttpPost]
 public JObject PostSavePage(JObject jObject)
 {        
     dynamic testObject = jObject;         
     // other stuff here
 }

I am new to this and I have a couple of questions around this area:

我是新手,我有几个关于这个领域的问题:

Am I doing something wrong in this particular example?

在这个特定的例子中我做错了什么吗?

Arguably, more importantly, is there a better way to pass in a dynamic JSON object (from an JavaScript AJAX post)?

可以说,更重要的是,有没有更好的方法来传递动态 JSON 对象(来自 JavaScript AJAX 帖子)?

采纳答案by davy

Thanks to everyone who helped here. Unfortunately, I never got to the bottom of what was wrong.

感谢所有在这里提供帮助的人。不幸的是,我从来没有深入了解错误的根源。

I ported the project over piece by piece to a new project and it works fine.

我将项目逐个移植到一个新项目中,并且运行良好。

For info, I have a RouteConfig class, which is quite simple at the moment:

有关信息,我有一个 RouteConfig 类,目前非常简单:

public class RouteConfig
{       
    private static string ControllerAction = "ApiControllerAction";

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapHttpRoute(
            name: ControllerAction,
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

My call into the API now uses JSON.Stringify:

我对 API 的调用现在使用 JSON.Stringify:

$.ajax("http://localhost:54997/api/values/PostSavePage/", {
    data:  JSON.stringify(jObject),                               
    contentType: 'application/json',
    type: 'POST'
});

The original API action works.

原始 API 操作有效。

Note, that I'm only playing with this at the moment so the code is not the best but I thought it may be useful in basic form in case someone else has a similar issue.

请注意,我目前只在玩这个,所以代码不是最好的,但我认为它在基本形式中可能有用,以防其他人有类似的问题。

回答by Mark Jones

As per Perception's comment your JSON doesn't look valid. Run it through JSONLintand you get:

根据 Perception 的评论,您的 JSON 看起来无效。通过JSONLint运行它,你会得到:

Parse error on line 1:
{    AlbumName: "Dirty De
-----^
Expecting 'STRING', '}'

Change it to have " around the field names:

将其更改为在字段名称周围带有 ":

{
    "AlbumName": "Dirty Deeds",
    "Songs": [
        {
            "SongName": "Problem Child"
        },
        {
            "SongName": "Squealer"
        }
    ]
}

Also have you tried swapping out your JObject for either a JToken or a Dynamic object (e.g. here)?

您是否也尝试过将 JObject 换成 JToken 或动态对象(例如此处)?

[HttpPost]
 public JObject PostSavePage(JToken testObject)
 {                
     // other stuff here
 }

OR

或者

 [HttpPost]
 public JObject PostSavePage(dynamic testObject)
 {                
     // other stuff here
 }