Reputation: 6636
I have a customer provided schema that includes an xs:anytype element in the wsdl.
The original generated code included a property of type object. Based on some other answers here on SO, I changed that to be of type XmlElement.
This works fine when I run my service inside visual studio (iis express), and I get the XML in the property correctly.
Sending the exact same SOAP messages to my app when deployed in IIS gives an error
Unable to cast object of type 'System.Xml.XmlText' to type 'System.Xml.XmlElement'.
Why is the deserialization behaving differently depending on the hosting? What is the proper type for my classes to hold the xs:anytype? How can I get this to behave consistently?
Note : I have accepted the first answer below as it solved the immediate problem, but see the second answer that I added for the ultimate root cause
Upvotes: 2
Views: 1134
Reputation: 6636
See also this related issue with different symptoms from the same root cause : WCF (de) serialization behaving differently under debug/Visual Studio and IIS
After burning an MSDN support ticket we have found the root cause of both issues. It was not IIS vs IIS express related, the content of the messages was subtly different.
The xsd:anyType allows for arbitrary XML to be sent. In this case, the Java application is sending HtmlEncoded xml as the payload for that element. rather than puking on this content and throwing a serialization error, WCF accepts it, and hydrates it as XmlText instead of XmlElement. However, after hydration, the full payload is not there, only a <
Making this issue confusing is that all debug windows, the WCF traces, etc all "fixed" the htmlEncoded content to display as valid XML. Therefore, when I copied the message out of the WCF Trace, and ran it manually from SoapUI to try and reproduce, the behavior changed!
I'm pushing back on the customer to fix the payload in the message they send, but if that is not possible, using a IDispatchMessageInspector.AfterReceiveRequest method will be able to convert the payload and send it through correctly.
Upvotes: 1
Reputation: 116711
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 XmlNode
. XmlNode
is the base class for both XmlText
and XmlElement
and represents any type of node in the XML DOM hierarchy.
Upvotes: 1