2011-12-14 120 views

回答

4

Content-Length标题计数字节,而不是字符。 String.Length统计字符。你可能想要的东西沿线

Response.AddHeader("Content-Length", 
        Response.ContentEncoding.GetByteCount(output).ToString()); 
+0

谢谢!奇迹般有效 :) – Johan 2011-12-14 16:00:57

2

你可能通过http请求传递XML?在这种情况下,数据以字节形式传递。你想要的字节长度,而不是字符长度。所以,得到这些字节的长度,而不是字符串的长度。

在这种情况下,它将使用编码,可能是UTF16,但C#将其称为unicode。

你有几个方法,可以帮助:

Encoding.Unicode.GetBytes(someString); 
Encoding.Unicode.GetByteCount(someString); 
2

如果XML不是太大,可以将其写入MemoryStream,然后传送MemoryStream的内容。

using (var ms = new MemoryStream()) 
{ 
    using (var writer = XmlWriter.Create(ms)) 
    { 
     // write your XML here... 
    } 
    Response.ContentLength = ms.Length; 
    Response.OutputStream.Write(ms.ToArray(), 0, ms.Length); 
}