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

所以如果我像这样从我的客户那里进来:

        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);
            }
        });
    }

数据是这样的:

{ "_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" }

在我的控制器中,我try 过:

public HttpResponseMessage Post([FromBody]JObject value)

and:

public HttpResponseMessage Post([FromBody]string value)

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

public HttpResponseMessage Post([FromBody]BsonDocument value)

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

推荐答案

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:

    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...

Json相关问答推荐

使用Jolt变换转换JsonArray以将关键字转移到内部JsonArray中

Vega-Lite(Deneb):难以将最小和最大值应用于折线图和文本标签以及线条末尾的点

PowerShell:使用JSON原生的Short命令处理JSON?

如何用JQ打印JSON文件的路径和键值

用 Jolt 替换 JSON 中的值

使用 JSON 和相对日期设置日历视图中 SharePoint 列表项的背景 colored颜色 格式

在 SQL 存储过程中使用参数 Select 值

在 VS Code 中将一个正则表达式替换为另一个正则表达式

ETCD 导出为 json 并从 base64 解码所有键/值到人类可读

如何在 Flutter 中遍历嵌套的动态 JSON 文件

PowerShell:如何将哈希表输出为 json 并使用 foreach 循环将其存储在变量中?

在 rust 中从 API 反序列化 serde_json

如何将西里尔字母转换为 utf16

JQuery,使用 GET 方法发送 JSON 对象

如何使用 CORS 实现 JavaScript Google Places API 请求

IE中Json响应下载(7~10)

使用 GSON 解析嵌套的 JSON 数据

数据包含连续问号时无法理解的 jQuery $.ajax() 行为

jQuery JSON 响应总是触发 ParseError

在自定义 JsonConverter 的 ReadJson 方法中处理空对象