問(wèn)題描述
在本地開(kāi)發(fā)的站點(diǎn),響應(yīng)頭中的中文可以正常顯示,部署到Azure App Service站點(diǎn)后,響應(yīng)中文亂碼。通過(guò)多方面驗(yàn)證,在代碼中設(shè)置Response的Headers會(huì)顯示亂碼,而直接配置在Web.Config中的Header則能正常顯示。
代碼中寫(xiě)的中文會(huì)亂碼
context.HttpContext.Response.Headers.Add("ChineseTest","中");
在web.config中的正常顯示

問(wèn)題解決
#使用UTF8來(lái)編碼中文字符
context.HttpContext.Response.Headers.Add("ChineseTest",HttpUtility.UrlEncode("中", System.Text.Encoding.UTF8));
#如果是需要下載文件或者設(shè)置文件名稱(chēng),所以需要使用Content
-Disposition頭stringheaderValue ="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);
問(wèn)題分析
Http Header默認(rèn)只接受ISO-8859-1的編碼,對(duì)于非ISO-8859-1/ASCII編碼的字符,如果直接傳輸?shù)脑?huà)會(huì)由于編碼不一致導(dǎo)致顯示亂碼的問(wèn)題。所以建議采用URL encode的方式,將中文通過(guò)這種方式傳輸,那么瀏覽器收到該header時(shí),會(huì)解碼之后顯示。 如:HttpUtility.UrlEncode("中文字符", System.Text.Encoding.UTF8)
另外,由于不同的瀏覽器支持的編碼不太相同,目前市面上的大部分瀏覽器都是支持使用utf-8編碼方式的,所以針對(duì)Safari瀏覽器顯示異常的問(wèn)題,在Content-Disposition后續(xù)推出的filename*參數(shù)中支持指定的編碼方式對(duì)filename進(jìn)行處理。 操作方式正是如下代碼:
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頭部中文編碼測(cè)試: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協(xié)議header中Content-Disposition中文文件名亂碼:https://my.oschina.net/pingpangkuangmo/blog/376332