【问题标题】:WCF Web API preview 6: No 'MediaTypeFormatter' is availableWCF Web API 预览 6:没有“MediaTypeFormatter”可用
【发布时间】:2012-01-12 03:55:50
【问题描述】:

我正在考虑在 WCF Web API Preview 6 中使用 HttpClient 来使用第三方服务。此第三方服务接受并返回 XML 格式的数据。他们的 HTTP 响应将 Content-Type 标头设置为 text/plain。似乎将响应 Content-Type 设置为 text/plain 会导致问题。我正在向服务提出如下请求:

Task<HttpResponseMessage> result = client.PostAsync(apiEndpoint, new ObjectContent(typeof (LeaveAccrualRequest), request));

使用 Fiddler,我可以看到请求转到服务并返回适当的预期响应。但是,当我尝试访问响应时,最终会出现以下 InvalidOperationException:

没有“MediaTypeFormatter”可用于读取媒体类型为“text/plain”的“LeaveAccrualResponse”类型的对象。

有没有办法告诉 HttpClient,即使 HTTP 响应说内容类型是 text/plain,它也应该将其作为 application/xml 处理?

【问题讨论】:

标签: wcf wcf-web-api


【解决方案1】:

您可以从 XmlMediaTypeFormatter 派生并添加您的“text/plain”标题:

public class TextPlainXmlMediaTypeFormatter : XmlMediaTypeFormatter {
    public TextPlainXmlMediaTypeFormatter() {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
    }
}

根据您的要求,在添加“text/plain:”之前删除所有其他支持的媒体类型可能是有意义的:

SupportedMediaTypes.Clear();

[更新]

访问您的请求内容并使用 ReadAsAsync 方法,该方法接受 IEnumerable

【讨论】:

  • 感谢您的回复!我按照您的建议添加了一个派生类,现在我提出这样的请求:PlainTextXmlFormatter formatter = new PlainTextXmlFormatter(); MediaTypeFormatterCollection 格式化程序 = new MediaTypeFormatterCollection{formatter}; Task result = client.PostAsync(apiEndpoint, new ObjectContent(typeof (LeaveAccrualRequest), request, formatters));仍然看到同样的错误。我也尝试删除所有其他受支持的媒体类型,但没有帮助
  • 对不起,我的建议是在服务器端。更新了我的答案。
猜你喜欢
  • 2019-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-13
  • 2015-01-31
  • 2012-05-11
  • 2012-09-13
相关资源
最近更新 更多