【问题标题】:No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'没有 MediaTypeFormatter 可用于从媒体类型为“text/plain”的内容中读取“String”类型的对象
【发布时间】:2012-09-12 19:27:51
【问题描述】:

情况是这样的:

他们是Servoy 中的外部网络服务,我想在 ASP.NET MVC 应用程序中使用此服务。

通过这段代码,我尝试从服务中获取数据:

HttpResponseMessage resp = client.GetAsync("http://localhost:8080/servoy-service/iTechWebService/axws/shop/_authenticate/mp/112818142456/82cf1988197027955a679467c309274c4b").Result;
resp.EnsureSuccessStatusCode();

var foo = resp.Content.ReadAsAsync<string>().Result;

但是当我运行应用程序时,我得到了下一个错误:

没有 MediaTypeFormatter 可用于读取“字符串”类型的对象 来自媒体类型为“text/plain”的内容。

如果我打开 Fiddler 并运行相同的 url,我会看到正确的数据,但内容类型是 text/plain。但是我在 Fiddler 中也看到了我想要的 JSON...

是否可以在客户端解决这个问题,或者是 Servoy 网络服务?

更新:
使用 HttpWebRequest 而不是 HttpResponseMessage 并使用 StreamReader 读取响应...

【问题讨论】:

    标签: c# .net asp.net-mvc json httpclient


    【解决方案1】:

    尝试改用 ReadAsStringAsync()。

     var foo = resp.Content.ReadAsStringAsync().Result;
    

    ReadAsAsync&lt;string&gt;() 不起作用的原因是因为ReadAsAsync&lt;&gt; 将尝试使用默认的MediaTypeFormatter 之一(即JsonMediaTypeFormatterXmlMediaTypeFormatter、...)来读取带有@ 的内容987654327@ 的text/plain。但是,没有一个默认格式化程序可以读取text/plain(它们只能读取application/jsonapplication/xml 等)。

    通过使用ReadAsStringAsync(),无论内容类型如何,内容都将被读取为字符串。

    【讨论】:

    • 我也有同样的问题,除了错误信息是"No MediaTypeFormatter is available to read an object of type 'Int32' from content with media type 'text/html'." int32有类似的解决方案吗?
    • Quanda:可以使用return JsonConvert.DeserializeObject(resultString);,result String是ReadAsStringAsync()之后的结果,JsonConvert是来自Newtonsoft.Json。您可以从 NuGet 下载此库。这对于便携式库也非常有用,不仅适用于 Int32,它几乎适用于所有类型或类。
    【解决方案2】:

    或者您也可以创建自己的MediaTypeFormatter。我将它用于text/html。如果您将text/plain 添加到其中,它也可以为您工作:

    public class TextMediaTypeFormatter : MediaTypeFormatter
    {
        public TextMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }
    
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
        }
    
        public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
        {
            using (var streamReader = new StreamReader(readStream))
            {
                return await streamReader.ReadToEndAsync();
            }
        }
    
        public override bool CanReadType(Type type)
        {
            return type == typeof(string);
        }
    
        public override bool CanWriteType(Type type)
        {
            return false;
        }
    }
    

    最后,您必须将其分配给 HttpMethodContext.ResponseFormatter 属性。

    【讨论】:

      【解决方案3】:

      我知道这是一个较老的问题,但我觉得t3chb0t 的回答让我找到了最好的方法,并且想分享。你甚至不需要去实现所有格式化程序的方法。我对正在使用的 API 返回的内容类型“application/vnd.api+json”执行了以下操作:

      public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
      {
          public VndApiJsonMediaTypeFormatter()
          {
              SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
          }
      }
      

      可以像下面这样简单地使用:

      HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
      HttpResponseMessage response = await httpClient.GetAsync("person");
      
      List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
      formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
      formatters.Add(new VndApiJsonMediaTypeFormatter());
      
      var responseObject = await response.Content.ReadAsAsync<Person>(formatters);
      

      超级简单,完全符合我的预期。

      【讨论】:

      • 我从媒体类型为“文本/日历”的内容中遇到了类型为“FileStreamResult”的对象的类似问题。我怎样才能解决这个问题? API 正在返回 iCal(文件流)
      猜你喜欢
      • 2016-06-29
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多