How to prevent .Net SOAP Serialization from eating NewLines
I'm using the built-in SOAP support in .Net through a wrapper class generated by Visual Studio from a WSDL.
Now, when I call one one of the methods on the wrapper and pass an object that conta开发者_开发技巧ins a string with CRLF (\r\n
), only the LF (\n
) will end up on the server. The same happens vice-versa. When the server sends a string containing CRLF, the wrapper will only spit out the LF.
I know this is a problem that can usually be avoided by supplying an own XmlWriter
to the XmlSerializer
, but I can't find a place where I could specify anything like that in the provided framework.
I almost want to go with the RegEx solution provided in this thread, but I have a hard time believing that there is nothing in place to prevent this issue.
Just for completeness sake, I didn't find a solution that provided what I was looking for. So the best solution for my case was going with the solution proposed in this answer.
Taken from here
XmlWriterSettings ws = new XmlWriterSettings();
ws.NewLineHandling = NewLineHandling.Entitize;
XmlSerializer ser = new XmlSerializer( typeof( Abc ) );
using (XmlWriter wr = XmlWriter.Create( "abc.xml", ws ))
{
ser.Serialize( wr, s );
}
Use a SoapExtension to escape the carriage returns in the stream headed to the service (SoapMessageStage.AfterSerialize).
This answer points to a good resource explaining how to implement one on v1.1 of the SOAP stuff; other examples are those which override ProcessMessage to remove invalid XML characters or log the entire SOAP conversation. (Configuration involves a SoapExtensionAttribute associating the extension with the web reference, typically setup in the web.config.)
精彩评论