这是我的解决方案。我在解析之前拦截服务响应并手动编辑它。
这是日期修复功能:
public class MessageDateFixer : IClientMessageInspector
{
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
return null;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
XmlDocument document = new XmlDocument();
MemoryStream memoryStream = new MemoryStream();
XmlWriter xmlWriter = XmlWriter.Create(memoryStream);
reply.WriteMessage(xmlWriter);
xmlWriter.Flush();
memoryStream.Position = 0;
document.Load(memoryStream);
FixMessage(document);
memoryStream.SetLength(0);
xmlWriter = XmlWriter.Create(memoryStream);
document.WriteTo(xmlWriter);
xmlWriter.Flush();
memoryStream.Position = 0;
XmlReader xmlReader = XmlReader.Create(memoryStream);
reply = Message.CreateMessage(xmlReader, int.MaxValue, reply.Version);
}
private static void FixMessage(XmlDocument document)
{
FixAllNodes(document.ChildNodes);
}
private static void FixAllNodes(XmlNodeList list)
{
foreach (XmlNode node in list)
{
FixNode(node);
}
}
private static void FixNode(XmlNode node)
{
if (node.Attributes != null &&
node.Attributes["xsi:type"] != null)
{
if (node.Attributes["xsi:type"].Value == "xsd:date")
{
node.Attributes["xsi:type"].Value = "xsd:dateTime";
node.InnerXml = node.InnerXml.Replace(" ", "T");
}
}
FixAllNodes(node.ChildNodes);
}
}
这是辅助类:
public class DateFixerBehavior : IEndpointBehavior
{
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new MessageDateFixer());
}
public void Validate(ServiceEndpoint endpoint)
{
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
}
这是用法:
PosterToolClient poster = new PosterToolClient();
poster.Endpoint.Behaviors.Add(new DateFixerBehavior());