ASP.NET: BOM in Server.Execute()

爱⌒轻易说出口 提交于 2019-12-24 00:54:30

问题


I'm using this to write to the Response stream:

    using (var writer = new StringWriter())
    {
        context.Server.Execute(virtualpath, writer);
        string s = writer.ToString().Replace(...);
        context.Response.Write(s);
    }

But I'm getting a byte order mark in the response. Am I screwing up the encoding? How do I NOT return the BOM?

EDIT: SOrry Rubens, my first example was incorrect.


回答1:


Try this:

context.Server.Execute(virtualpath, context.Response.Output);

EDIT: So, try this to force your encoding:

MemoryStream ms = new MemoryStream();
StreamWriter writer = new StreamWriter(ms);
context.Server.Execute(virtualpath, writer);
context.Response.Write(Encoding.UTF8.GetString(ms.ToArray()).Replace(...));



回答2:


Server.Execute() returns an encoded stream, but StringWriter() is intended to store simple .NET strings (which are 16-bit Unicode and don't have a BOM) and doesn't know how to decode the incoming bytes. So, the BOM in the response becomes literal characters in your string.

Try writing to a MemoryStream() instead, then decode that back into a string using whichever encoding (UTF-8 or whatever) that the Server.Execute() is passing back. Then you can parse it and write it back to your Response.



来源:https://stackoverflow.com/questions/1745392/asp-net-bom-in-server-execute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!