Mou*_*ark 3 c# httpresponse character-encoding windows-1252
我正在尝试在HTTP响应中发送一些在Windows 1252中编码的数据(它是一个CSV文件),但在某些地方,它会被重新编码为UTF-8(无BOM).如何确保数据保持正确的编码?
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();
Run Code Online (Sandbox Code Playgroud)
你打电话的时候
HttpContext.Current.Response.Write(someString)
Run Code Online (Sandbox Code Playgroud)
输入someString将使用.NET的内部字符串表示形式(实际上是UTF-16).要实际发送输出,必须进行转换.默认情况下,此转换将为UTF-8(因为它有效地支持整个Unicode).
该Charset属性只是设置HTTP响应头.但是并不存在ContentEncoding实际控制字符串发送方式的属性.
所以你错过了
HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("Windows-1252")
Run Code Online (Sandbox Code Playgroud)
有关System.Text.Encoding支持的编码列表,请参阅说明.
| 归档时间: |
|
| 查看次数: |
6996 次 |
| 最近记录: |