将JSON发布到Web API 2时出错:此资源不支持请求实体的媒体类型"text/plain"

tob*_*777 11 json asp.net-web-api asp.net-web-api2

我有这门课:

public class MyClass
{
    public MyClass() { Secret = "Don't tell me"; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Description { get; set; }
    private string Secret { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

而这个WEB API方法:

        // POST api/fixture
    public HttpResponseMessage Post(MyClass value)
    {
        return new HttpResponseMessage(HttpStatusCode.Created);
    }
Run Code Online (Sandbox Code Playgroud)

我已将Web API设置为返回JSON而不是XML,并且我没有对默认配置进行任何其他更改.我正在尝试使用Firefox的RESTClient扩展来测试此方法.这是我的要求:

POST localhost:XXXX/api/fixture
Content-Type: application/json
Accept: application/json
Content-Length: 60

{
 value : { "Name":"Cosby","Age":"13","Description":"OK" }
}
Run Code Online (Sandbox Code Playgroud)

但是我收到了这个错误:

{"Message":"此资源不支持请求实体的媒体类型'text/plain'.","ExceptionMessage":"没有MediaTypeFormatter可用于从媒体类型'文本的内容中读取'MyClass'类型的对象/plain'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":"at System.Net.Http.HttpContentExtensions.ReadAsAsync [T](HttpContent内容,类型类型,IEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1格式化程序,IFormatterLogger formatterLogger,CancellationToken cancellationToken)\ r \n在System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage请求,类型类型,IEnumerable`1格式化程序,IFormatterLogger formatterLogger,CancellationToken cancellationToken)"}

编辑:

我不明白,因为似乎甚至没有调用该方法.如果我调试,我看到构造函数被调用,然后没有调用其他方法.没有例外.

我现在已经讨论了很多这个问题了.我发现,当Content-Type设置不正确时,通常会发生此问题,但由于请求甚至没有处理,因此它似乎不是我的情况.

任何的想法 ?

谢谢

Azl*_*mal 15

POSTMAN中,您只需将设置更改为application/json.请参考下图.

应用程序/ JSON


Baq*_*qvi 10

可能您需要在HTTP请求标头中添加以下内容:

Content-Type: application/json
Run Code Online (Sandbox Code Playgroud)


mas*_*son 9

您正在发送application/json正文中的内容类型,而不是标题.所以你的POST请求默认为text/plain.RestClient扩展有一个单独的位置来输入标题.

如果您对通过网络发送的内容有疑问,请查看浏览器开发人员工具中的"网络"选项卡,或使用Fiddler等工具查看网络流量.


Jso*_*son 5

使用 Postman 测试您的 Web API,将其配置为 header: content-type: application/json 因为这是一个 POST 请求,所以您必须放置原始 json 数据。