2011-06-14 89 views
1

我寫了一個ASHX通用處理程序來輸出XML。但是,由於某些原因,ASP.net會在打破XML的輸出結尾添加大量空白字符。爲什麼ASP.net在我的ASHX文件的輸出末尾寫入空格?

我的代碼如下所示:

context.Response.ContentType = 「文本/ 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確實包含的無空白的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將這些空格添加到輸出中,我該怎麼辦?

+0

你的XML看起來像什麼? – Kev 2011-06-14 16:54:33

回答

1

從MS2.GetBuffer()切換到MS2.ToArray()。您正在從MemoryStream中讀取緩衝區,該緩衝區是爲提高效率而預先分配的。你只需要使用的數據,而不是整個緩衝區。

0

而不是序列化到MemoryStream,你應該直接序列化到Response.Output
這應該可以解決問題。

相關問題