8

AJAX 调用

$.ajax({
    url: '/api/Inventory',
    cache: false,
    type: 'POST',
    data: json,
    contentType: 'application/json, charset=utf-8',
    statusCode: {
        201: function (data) {
            console.log(data);
            viewModel.items.push(data);
        }
    }
});

发送数据 ( json) / 请求负载

{"Id":0,"Upc":"3456789012","Quantity":"200","Category":"Vodka","TransactionType":"Audit","MetaData":"ABSOLUT 750ml"} 

响应错误

没有 MediaTypeFormatter 可用于从媒体类型为“未定义”的内容中读取类型为“InventoryItem”的对象。”

路由 POST 方法

public HttpResponseMessage PostItem(InventoryItem item)

JSON 字符串中的所有属性都存在于InventoryItem模型中。

关于复杂类型的类似问题建议从 Beta 升级到 RC 以修复模型绑定更改,我已经这样做了。

如果问题不明显,我该如何纠正这个错误?如果我将 [FromUri] 属性添加到 Routed POST 方法,则 AJAX 调用会正确路由,但InventoryItem. 如果您需要任何其他信息,请告诉我。

4

1 回答 1

19
contentType: 'application/json, charset=utf-8',

should be:

contentType: 'application/json; charset=utf-8',

Notice the usage of ; instead of , which is the correct separator between the content type and the charset. Also if you follow standard RESTful conventions your controller action should be called Post and not PostItem as you have shown:

public HttpResponseMessage Post(InventoryItem item)
{
    ...
}
于 2012-06-24T19:58:37.180 回答