将html响应内容的字符集设置为1252 [英] Setting the charset of html response content to 1252
问题描述
我试图在HTTP响应中发送一些在Windows 1252中编码的数据(它是一个CSV文件),但在某种程度上它被重新编码为UTF-8(没有BOM)。如何确保数据保持正确的编码?
var sb = new StringBuilder
//从sb中的windows-1252字符串构建文件...
HttpContext.Current.Response.Clear();
HttpContextCurrent.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader(content-disposition,string.Format(filename = \{0} \.csv,fileName));
HttpContext.Current.Response.ContentType =text / csv; charset = windows-1252;
HttpContext.Current.Response.Charset =windows-1252;
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
调用
HttpContext.Current.Response.Write(someString)
输入 someString
将在.NET的内部字符串表示(实际上是UTF-16)。要实际发送输出,必须进行转换。默认情况下,这种转换将是UTF-8(因为它有效地支持整个Unicode)。
Charset
属性只是设置HTTP响应头。但不包括 ContentEncoding $ c $
$ b
HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding(Windows-1252)
请参阅 System.Text.Encoding的说明
支持的编码列表。
I'm trying to send some data encoded in Windows 1252 (it's a CSV file) in an HTTP response, but somewhere along the way it's getting re-encoded to UTF-8 (no BOM). How can I make sure that the data stays in the correct encoding?
var sb = new StringBuilder();
// Build the file from windows-1252 strings in the sb...
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("filename=\"{0}\".csv", fileName));
HttpContext.Current.Response.ContentType = "text/csv;charset=windows-1252";
HttpContext.Current.Response.Charset = "windows-1252";
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
When you call
HttpContext.Current.Response.Write(someString)
the input someString
will be in .NET's internal string representation (actually UTF-16). To actually send the output this has to be converted. By default this conversion will be to UTF-8 (because it efficiently supports the whole of Unicode).
The Charset
property simply sets the HTTP response headers. But not there is also a ContentEncoding
property to actually control how strings are sent.
So you are missing
HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("Windows-1252")
See the description of System.Text.Encoding
for a list of supported encodings.
这篇关于将html响应内容的字符集设置为1252的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!