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

后端 未结 3 695
迷失自我
迷失自我 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 07:40

    You can use a StringWriter that will force UTF8. Here is one way to do it:

    public class Utf8StringWriter : StringWriter
    {
        // Use UTF8 encoding but write no BOM to the wire
        public override Encoding Encoding
        {
             get { return new UTF8Encoding(false); } // in real code I'll cache this encoding.
        }
    }
    

    and then use the Utf8StringWriter writer in your code.

    using (StringWriter writer = new Utf8StringWriter())
    {
        XmlSerializer xml = new XmlSerializer(typeof(T));
        xml.Serialize(writer, Data);
        httpContextBase.Response.Write(writer);
    }
    

    answer is inspired by Serializing an object as UTF-8 XML in .NET

提交回复
热议问题