C# 如何将任意 json 对象发布到 webapi

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13573384/
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-08-10 09:03:21  来源:igfitidea点击:

how to post arbitrary json object to webapi

c#jsonmongodbasp.net-web-api

提问by Jonathan

How do I / is it possible to pass in a json object to a webapi controller (POST) and nothave a class to map it to, but rather handle it as arbitrary content?

我如何/是否可以将 json 对象传递给 webapi 控制器(POST)并且没有将其映射到的类,而是将其作为任意内容处理?

So if I pass in from my client like so:

所以如果我像这样从我的客户那里传入:

        createRecord: function (model, data, callback, callbackParams) {
        var request = jQuery.ajax({
            type: "POST", // default = GET,
            url: '/api/' + model + '/',
            data: data,
            contentType: 'application/json',
            success: function (msg) {
                $('#results').text(msg);
                if (callback) // only fire a callback if it has been specified
                    callback(msg, callbackParams);
            },
            error: function (jqXHR, textStatus) {
                alert('Request failed: ' + textStatus);
            }
        });
    }

and data is something like:

和数据是这样的:

{ "_id" : ObjectId("5069f825cd4c1d590cddf206"), "firstName" : "John", "lastName" : "Smith", "city" : "Vancouver", "country" : "Canada" }

My controller will be able to parse it? And next time the data may not match that signature (eg:

我的控制器能够解析它吗?下次数据可能与该签名不匹配(例如:

{ "_id" : ObjectId("5069f825cd4c1d56677xz6"), "company" : "Acme" }

In my controller, I have tried:

在我的控制器中,我尝试过:

public HttpResponseMessage Post([FromBody]JObject value)

and:

和:

public HttpResponseMessage Post([FromBody]string value)

and (because this is actually to work with a mongo db):

并且(因为这实际上是与 mongo db 一起使用):

public HttpResponseMessage Post([FromBody]BsonDocument value)

but it looks like the object mapper wants to map to something other than string...

但看起来对象映射器想要映射到字符串以外的东西......

采纳答案by Maggie Ying

You can have your post method that takes in a HttpRequestMessage to by pass the model binding logic and you can read the content of the request directly:

你可以让你的 post 方法接受一个 HttpRequestMessage 来绕过模型绑定逻辑,你可以直接读取请求的内容:

    public HttpResponseMessage Post(HttpRequestMessage req)
    {
        var data = req.Content.ReadAsStringAsync().Result; // using .Result here for simplicity...
        ...

    }

By the way, the reason why the action that takes in JObject doesn't work is because of 'ObjectId("...")' that is used as the value of "_id" in your data...

顺便说一下,在 JObject 中执行的操作不起作用的原因是因为 'ObjectId("...")' 在您的数据中用作“_id”的值...

回答by Maggie Ying

In your input, "_id": ObjectId("5069f825cd4c1d590cddf206")is what is breaking the JSON materialization on the server. Removing ObjectIdand using "_id" : "5069f825cd4c1d590cddf206"works with JObjectas well as Dictionary<string, object>

在您的输入中,"_id": ObjectId("5069f825cd4c1d590cddf206")是什么破坏了服务器上的 JSON 实现。删除ObjectId和使用"_id" : "5069f825cd4c1d590cddf206"作品JObject以及Dictionary<string, object>

回答by Bes Ley

We passed json object by jquery, and parse it in dynamic object. it works fine. this is sample code:

我们通过 jquery 传递 json 对象,并在动态对象中解析它。它工作正常。这是示例代码:

ajaxPost:

...
Content-Type: application/json,
data: {
          "name": "Hyman", 
          "age": "12"
      }
...

webapi:

网络接口:

[HttpPost]
public string DoJson2(dynamic data)
{
    string name = data.name;
    int age = data.age;

    return name;
}

similary question on stackoverflow: WebAPI Multiple Put/Post parameters

stackoverflow 上的类似问题: WebAPI Multiple Put/Post parameters

回答by Javier Ramírez

It is very easy, you just need to put the Accept Header to "application/json".

很简单,你只需要把 Accept Header 放到 "application/json" 中。