为什么ASP.net在ASHX文件的输出末尾写入空格?

问题描述

| 我已经编写了一个ASHX通用处理程序来输出XML。但是,由于某种原因,ASP.net将大量空白字符附加到输出的末尾,这会破坏XML。 我的代码如下所示: context.Response.ContentType = \“ text / xml \”;
        XmlSerializer oSerializer = new XmlSerializer(typeof(ModelXml[]),new XmlRootAttribute(\"rows\"));
        System.IO.MemoryStream ms2 = new System.IO.MemoryStream();
        System.Xml.XmlTextWriter tw = new System.Xml.XmlTextWriter(ms2,new System.Text.UTF8Encoding());
        oSerializer.Serialize(tw,models);
        string s = System.Text.Encoding.UTF8.GetString(ms2.GetBuffer());
        tw.Close();
        ms2.Close();

        context.Response.Write(s.Trim());
        context.Response.End();
当我通过调试器运行此代码时,我看到字符串
s
确实包含不带WHITESPACE的XML数据。但是,当我将Internet Explorer指向此文件时,出现以下错误
The XML page cannot be displayed 
Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button,or try again later. 

--------------------------------------------------------------------------------

Invalid at the top level of the document. Error processing resource \'http://localhost:5791/XXXXX.ashx\'. 
当我在记事本中查看页面源时,我看到该文件以正确的XML开头,但是末尾有许多空格。如果删除这些空格,则XML文件可以在我的浏览器和应用程序中正常工作。 为什么ASP.net将这些空格附加到我的输出中,我该怎么办?     

解决方法

        从MS2.GetBuffer()切换到MS2.ToArray()。您正在从MemoryStream中读取缓冲区,该缓冲区已预先分配以提高效率。您只需要使用的数据,而不是整个缓冲区。     ,        而不是序列化为
MemoryStream
,您应该直接序列化为
Response.Output
。 这应该可以解决问题。