xs:anytype 的 WCF 消息导致序列化问题

WCF message with xs:anytype causing serialization problems

我有一个客户提供的架构,它在 wsdl 中包含一个 xs:anytype 元素。

原始生成的代码包含一个 属性 类型的对象。基于 SO 上的其他一些答案,我将其更改为 XmlElement 类型。

当我 运行 我的服务在 visual studio (iis express) 中时,这工作正常,我在 属性 中正确地得到了 XML。

在 IIS 中部署时向我的应用程序发送完全相同的 SOAP 消息会出现错误

无法将类型 'System.Xml.XmlText' 的对象转换为类型 'System.Xml.XmlElement'。

为什么反序列化的行为因托管而异?我的 类 持有 xs:anytype 的正确类型是什么?我怎样才能让它表现一致?

注意:我接受了下面的第一个答案,因为它解决了眼前的问题,但请参阅我为最终根本原因添加的第二个答案

XmlText represents a string literal in XML -- the character data of an element rather than a full element. It appears from the error that your XML might contain a complete element or might contain character data. The serializer is trying to save the character data as XmlText, but failing with an invalid cast error. To handle this, switch your property type from XmlElement to XmlNodeXmlNodeXmlTextXmlElement 的基础 class,代表 XML DOM 层次结构中的任何类型的节点。

另请参阅具有相同根本原因的不同症状的相关问题:

在刻录 MSDN 支持票证后,我们找到了这两个问题的根本原因。这与 IIS 与 IIS Express 无关,消息的内容略有不同。

xsd:anyType 允许发送任意 XML。在这种情况下,Java 应用程序发送 HtmlEncoded xml 作为该元素的有效负载。 WCF 不会在该内容上呕吐并抛出序列化错误,而是接受它,并将其合成为 XmlText 而不是 XmlElement。然而,水合作用后,完整的有效载荷不存在,只有 <

使这个问题令人困惑的是所有调试 windows、WCF 跟踪等都 "fixed" htmlEncoded 内容显示为有效 XML。因此,当我从 WCF Trace 中复制消息,并 运行 从 SoapUI 手动尝试重现时,行为发生了变化!

我正在敦促客户修复他们发送的消息中的负载,但如果这不可能,使用 IDispatchMessageInspector.AfterReceiveRequest 方法将能够转换负载并正确发送.