character (UTF-8 BOM) in middle of ASP.NET response due to HttpResponse.TransmitFile()

谁说胖子不能爱 提交于 2020-01-06 08:50:35

问题


I've seen this post:  characters appended to the begining of each file.

In that case, the author was manually reading the source file and writing the contents. In my case, I'm abstracting it away via HttpRequest.TransmitFile():

public void ProcessRequest(HttpContext context)
{
    HttpRequest req = context.Request;
    HttpResponse resp = context.Response;

    resp.ContentType = "application/javascript";

    resp.TransmitFile("foo.js");
    resp.TransmitFile("bar.js");
    resp.TransmitFile("baz.js");
}

The .js files are indeed encoded in UTF-8. This means the  BOM incorrectly appears at the beginning of each but the first file.

The nice things about TransmitFile() are that (a) it abstracts away the entire reading+writing process, and (b) it's optimized to not read the files into memory first -- which is hugely important when the files are large and/or you have many concurrent requests. But the flip side is that I'm not able to re-encode it into UTF-8 without the BOM. (I guess this is an example of a leaky abstraction.)

Is there any elegant way to solve this problem? Thanks!


回答1:


Closing the loop on this: TransmitFile() transmits the raw bytes of the file, so if the files are encoded in UTF-8 with a BOM and you transmit multiple files, you'll transmit multiple BOMs.

If you read the files yourself into memory as strings and transmit those strings, you won't get this issue. We ended up going with simply encoding the files as UTF-8 without the BOM or as ANSI.



来源:https://stackoverflow.com/questions/1376602/%c3%af-character-utf-8-bom-in-middle-of-asp-net-response-due-to-httpresponse-tran

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