【Azure 应用服务】App Service站点Header头中的中文信息显示乱码?当下载文件时,文件名也是乱码? - LuBu0505/My-Code GitHub Wiki

问题描述

在本地开发的站点,响应头中的中文可以正常显示,部署到Azure App Service站点后,响应中文乱码。通过多方面验证,在代码中设置Response的Headers会显示乱码,而直接配置在Web.Config中的Header则能正常显示。

代码中写的中文会乱码 context.HttpContext.Response.Headers.Add("ChineseTest", "中");

在web.config中的正常显示

  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <httpProtocol>
      <customHeaders>
        <add name="abc" value="中"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer> 

问题解决


#使用UTF8来编码中文字符
context.HttpContext.Response.Headers.Add("ChineseTest", HttpUtility.UrlEncode("中", System.Text.Encoding.UTF8));



#如果是需要下载文件或者设置文件名称,所以需要使用Content-Disposition头
string headerValue = "attachment;";
headerValue += " filename=" + HttpUtility.UrlEncode("中.txt", System.Text.Encoding.UTF8) + ";";
headerValue += " filename*=utf-8''" + HttpUtility.UrlEncode("中.txt", System.Text.Encoding.UTF8);
HttpContext.Response.Headers.Add("Content-Disposition", headerValue);

问题分析

Http Header默认只接受ISO-8859-1的编码,对于非ISO-8859-1/ASCII编码的字符,如果直接传输的话会由于编码不一致导致显示乱码的问题。所以建议采用URL encode的方式,将中文通过这种方式传输,那么浏览器收到该header时,会解码之后显示。 如:HttpUtility.UrlEncode("中文字符", System.Text.Encoding.UTF8)

另外,由于不同的浏览器支持的编码不太相同,目前市面上的大部分浏览器都是支持使用utf-8编码方式的,所以针对Safari浏览器显示异常的问题,在Content-Disposition后续推出的filename*参数中支持指定的编码方式对filename进行处理。 操作方式正是如下代码:

string headerValue = "attachment;";
headerValue += " filename=" + HttpUtility.UrlEncode("中.txt", System.Text.Encoding.UTF8) + ";";
headerValue += " filename*=utf-8''" + HttpUtility.UrlEncode("中.txt", System.Text.Encoding.UTF8);
HttpContext.Response.Headers.Add("Content-Disposition", headerValue);

参考资料

Content-Disposition头部中文编码测试:http://imushan.com/2019/04/10/network/Content-Disposition%E5%A4%B4%E9%83%A8%E4%B8%AD%E6%96%87%E7%BC%96%E7%A0%81%E6%B5%8B%E8%AF%95/

HTTP协议header中Content-Disposition中文文件名乱码:https://my.oschina.net/pingpangkuangmo/blog/376332

⚠️ **GitHub.com Fallback** ⚠️