问题描述
我正在研究在WCF Web API Preview 6中使用HttpClient来使用第三方服务.该第三方服务接受并返回XML格式的数据.他们的HTTP响应的Content-Type标头设置为text/plain.似乎将响应Content-Type设置为text/plain会引起问题.我对服务的请求如下:
I'm looking at using HttpClient in WCF Web API Preview 6 to consume a third party service. This third party service accepts and returns XML formatted data. Their HTTP responses have the Content-Type header set to text/plain. It appears that having the response Content-Type set to text/plain is causing problems. I'm making the request to the service as follows:
Task<HttpResponseMessage> result = client.PostAsync(apiEndpoint, new ObjectContent(typeof (LeaveAccrualRequest), request));
使用Fiddler,我可以看到请求转到了服务,并且适当的预期响应又回来了.但是,当我尝试访问响应时,最终出现以下InvalidOperationException:
Using Fiddler, I can see the request go to the service and an appropriate, expected response come back. However when I try to access the response, I end up with the following InvalidOperationException:
没有'MediaTypeFormatter'可以读取类型为'text/plain'的'LeaveAccrualResponse'类型的对象.
是否有一种方法可以告诉HttpClient,即使HTTP响应指出内容类型为text/plain,也应将其作为application/xml来处理?
Is there a way to tell HttpClient that even though the HTTP response says the content type is text/plain, it should handle it as application/xml?
推荐答案
您可以从XmlMediaTypeFormatter派生并添加"text/plain"标头:
You could derive from XmlMediaTypeFormatter and add your "text/plain" header:
public class TextPlainXmlMediaTypeFormatter : XmlMediaTypeFormatter {
public TextPlainXmlMediaTypeFormatter() {
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}
}
根据您的要求,在添加文本/纯文本:
Depending on your requirements it could make sense to remove all other supported media types before adding "text/plain:
SupportedMediaTypes.Clear();
[更新]
访问您的请求内容并使用ReadAsAsync< T>覆盖IEnumerable< MediaTypeFormatter>的方法.
Access your requests Content and use the ReadAsAsync<T> method overlaod which accepts an IEnumerable<MediaTypeFormatter>.
这篇关于WCF Web API预览6:没有"MediaTypeFormatter"可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!