How to return xml as UTF-8 instead of UTF-16

后端 未结 3 697
迷失自我
迷失自我 2020-12-29 07:15

I am using a routine that serializes . It works, but when downloaded to the browser I see a blank page. I can view the page source or open the download

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 07:46

    Encoding of the Response

    I am not quite familiar with this part of the framework. But according to the MSDN you can set the content encoding of an HttpResponse like this:

    httpContextBase.Response.ContentEncoding = Encoding.UTF8;
    

    Encoding as seen by the XmlSerializer

    After reading your question again I see that this is the tough part. The problem lies within the use of the StringWriter. Because .NET Strings are always stored as UTF-16 (citation needed ^^) the StringWriter returns this as its encoding. Thus the XmlSerializer writes the XML-Declaration as

    
    

    To work around that you can write into an MemoryStream like this:

    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 linked by jtm001. Condensed the solution there is to provide the XmlSerializer with a custom XmlWriter that is configured to use UTF8 as encoding.

    Athari proposes to derive from the StringWriter and advertise the encoding as UTF8.

    To my understanding both solutions should work as well. I think the take-away here is that you will need one kind of boilerplate code or another...

提交回复
热议问题