0

我正在使用发布候选者开发 MVC4 api。当我使用 Content-Type: application/json 执行 GET 时出现错误我收到此错误:“JsonNetFormatter”类型的媒体类型格式化程序不支持写入,因为它没有实现 WriteToStreamAsync 方法。

我相信我是!

public Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext)
    {
        var task = Task.Factory.StartNew(() =>
        {
            var settings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore,
            };

            string json = JsonConvert.SerializeObject(value, Formatting.Indented,
                                                      new JsonConverter[1] { new IsoDateTimeConverter() });

            byte[] buf = System.Text.Encoding.Default.GetBytes(json);
            stream.Write(buf, 0, buf.Length);
            stream.Flush();
        });

        return task;
    }

我看过一个覆盖此方法的示例,但我收到一个错误,即没有合适的方法可以覆盖。我猜这是 System.Net.Http.Formatting.dll 的版本控制问题,但我仔细检查了版本,它看起来不错:

// Type: System.Net.Http.Formatting.MediaTypeFormatter
// Assembly: System.Net.Http.Formatting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// Assembly location: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Net.Http.Formatting.dll
4

1 回答 1

0

我在如何实现该方法时犯了一个错误。就像错误所说的那样。HttpContent 应将 HttpContentHeaders 更改为:

public override Task WriteToStreamAsync(Type type, object value,
                                    Stream stream,
                                    HttpContentHeaders content,
                                    TransportContext transportContext)
于 2012-06-06T15:47:41.407 回答