C# 没有 MediaTypeFormatter 可用于读取“InventoryItem”类型的对象

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

No MediaTypeFormatter is available to read an object of type 'InventoryItem'

c#asp.net-mvcasp.net-web-api

提问by Josh

AJAX Call

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

Sent Data (json) / Request Payload

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

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

Response Error

响应错误

No MediaTypeFormatter is available to read an object of type 'InventoryItem' from content with media type ''undefined''."

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

Routed POST method

路由POST方法

public HttpResponseMessage PostItem(InventoryItem item)

All properties in the JSON string are present in the InventoryItemmodel.

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

A similar questionregarding complex types suggested upgrading from Beta to RC to fix a model binding change, which I have done.

一个类似的问题就复杂类型建议升级从Beta到RC来修复模型绑定的变化,这是我做的事。

If the question isn't obvious, how do I rectify this error? If I add the the [FromUri] attribute to the Routed POST method, then the AJAX call is routed properly, but with an empty InventoryItem. If you need any other information, please let me know.

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

采纳答案by Darin Dimitrov

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 Postand not PostItemas you have shown:

注意的使用;,而不是,其内容类型和字符集之间的正确分离器。此外,如果您遵循标准 RESTful 约定,则应调用控制器操作,Post而不是PostItem如您所示:

public HttpResponseMessage Post(InventoryItem item)
{
    ...
}