【发布时间】:2012-11-05 02:36:40
【问题描述】:
无论内容类型如何,如何强制 WCF Rest 客户端使用 Json 反序列化器?
我正在通过 WCF 调用基于 REST 的 Web 服务。
服务返回 JSON 正文,但内容类型为“Application/xml”。 WCF 框架现在给了我 XmlException。
public class MessageFormatter : IClientMessageFormatter
{
private readonly IClientMessageFormatter _formatter;
public MessageFormatter(IClientMessageFormatter formatter)
{
_formatter = formatter;
}
public object DeserializeReply(System.ServiceModel.Channels.Message message, object[] parameters)
{
return _formatter.DeserializeReply(message, parameters);
}
}
_formatter.DeserializeReply 正在抛出 XmlException。我在任何地方都找不到任何示例来强制回复时进行 json 反序列化。
编辑 - 鼠标悬停时的“消息”对象抛出“{...错误读取正文:System.Xml.XmlException:根级别的数据无效。第1行,位置1....}”
我的另一个项目中与不同的 REST 服务(Picasa Web 服务)通信的同一个对象有一个看起来像 JSON 对象的 xml 序列化版本的东西?所以这个问题似乎更进一步。我需要找到这个对象的来源。我会去玩 MessageEncoder 类。
编辑 - (添加更多信息)
public class MyBinding : WebHttpBinding
{
public MyBinding(WebHttpSecurityMode mode)
: base(mode)
{
}
public override BindingElementCollection CreateBindingElements()
{
var result = base.CreateBindingElements();
var replacements = result.OfType<MessageEncodingBindingElement>().ToList();
foreach (var messageEncodingBindingElement in replacements)
{
var index = result.IndexOf(messageEncodingBindingElement);
result.Remove(messageEncodingBindingElement);
result.Insert(index, new MyMessageEncodingBindingElement(messageEncodingBindingElement));
}
return result;
}
}
public class MyMessageEncodingBindingElement : MessageEncodingBindingElement
{
private readonly MessageEncodingBindingElement _element;
public MyMessageEncodingBindingElement(MessageEncodingBindingElement element)
{
_element = element;
}
public override BindingElement Clone()
{
var result = _element.Clone();
if (result is MessageEncodingBindingElement)
return new MyMessageEncodingBindingElement(result as MessageEncodingBindingElement);
return result;
}
public override MessageEncoderFactory CreateMessageEncoderFactory()
{
return new MyMessageEncoderFactory(_element.CreateMessageEncoderFactory());
}
}
即使在设置断点时遇到构造函数和 Clone 方法,也永远不会调用 CreateMessageEncoderFactory() 方法。有什么帮助吗?我正在尝试设置自定义MessageEncoder和MessageEncoderFactory类来修改Message对象的实例化过程。
【问题讨论】:
-
顺便说一句,来自 iContact.com 背后的优秀团队。 xml 上没有 xml 声明。 json 响应的内容类型错误。如果节点的名称没有用双引号括起来,反序列化 json 会出现问题。哪个不称职的白痴在那里管理他们的团队。他们甚至无法通过垃圾邮件过滤器收到一封“欢迎”信。
-
您是否将 WebGetAttribute / WebInvokeAttribute 的 RequestFormat 和 ResponseFormat 属性设置为 WebMessageFormat.Json?即 [WebGet(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
-
是的,我是。 [WebInvoke(Method = "GET", UriTemplate = "messages", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
-
您能否检查您发送的 http 标头以查看它是发送“Accept”标头还是仅发送“Content-Type”?
-
对不起,我已经尽力了,但看起来这个问题超出了我的范围。祝你好运。 (老实说,您可能只想给他们打个电话,看看他们以前是否遇到过这个问题。他们可能希望“Accept”标头是非标准的确切字符串)