WCF Method is returning xml fragment but no xml UTF-8 header
My method does not return the header, just the root element xml.
i开发者_高级运维nternal Message CreateReturnMessage(string output, string contentType)
{
// create dictionaryReader for the Message
byte[] resultBytes = Encoding.UTF8.GetBytes(output);
XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(resultBytes, 0, resultBytes.Length, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null);
if (WebOperationContext.Current != null)
WebOperationContext.Current.OutgoingResponse.ContentType = contentType;
// create Message
return Message.CreateMessage(MessageVersion.None, "", xdr);
}
However, the output I get is:
<Test>
<Message>Hello World!</Message>
</Test>
I would like the output to render as:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Test>
<Message>Hello World!</Message>
</Test>
Have a look at this URL http://blogs.msdn.com/b/wifry/archive/2007/05/15/wcf-bodywriter-and-raw-xml-problems.aspx Pass the xml string to the custom bodywriter and it will output xml declaration
so assuming output
param is coming in as...
<Test>
<Message>Hello World!</Message>
</Test>
What do you expect to happen? You aren't writing xml, just reading the output
string through a reader. The reader class won't add anything to your fragment, it's a reader, not a writer.
You could so something like this instead...It will parse your output as xml and then you can add a declaration before giving it to the message.
var output = "<Test><Message>Hello World!</Message></Test>";
var xd = XDocument.Parse(output);
xd.Declaration = new XDeclaration("1.0", "utf-8", "yes");
return Message.CreateMessage(version, messageFault, xd.ToString());
精彩评论