Response coding
I am not completely familiar with this part of the structure. But according to MSDN, you can set the encoding of the HttpResponse content as follows:
httpContextBase.Response.ContentEncoding = Encoding.UTF8;
The encoding that XmlSerializer sees
After reading your question again, I see that this is the hard part. The problem is using StringWriter . Since .NET strings are always stored as UTF-16 (reference ^^), StringWriter returns this as its encoding. Thus, the XmlSerializer writes the XML declaration as
<?xml version="1.0" encoding="utf-16"?>
To get around this, you can write to a MemoryStream as follows:
using (MemoryStream stream = new MemoryStream()) using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8)) { XmlSerializer xml = new XmlSerializer(typeof(T)); xml.Serialize(writer, Data); // I am not 100% sure if this can be optimized httpContextBase.Response.BinaryWrite(stream.ToArray()); }
Other approaches
Another edit: I just noticed this SO answer related to jtm001. The condensed solution is to provide the XmlSerializer custom XmlWriter that is configured to use UTF8 as the encoding.
Athari offers to extract from StringWriter and advertise encoding as UTF8.
As far as I understand, both solutions should work. I think the check out here is that you will need one type of template code or another ...
NobodysNightmare Sep 08 '14 at 19:36 2014-09-08 19:36
source share