Skip to main content
 首页 » 编程设计

c#之Web 响应 header 中的 Unicode 数据

2024年01月01日41mfrbuaa

我开发了 web api,它使用 POST 方法接受文件,进行操作并使用 HTTP 响应将它们返回。 Web api 在 http header 中返回附加数据,如输出文件名。问题是,然后我使用 HttpWebResponse 发布和接收响应,我在响应 header 值中得到乱码文件名,并且 unicode 字符丢失。

例如,如果我提交 наталья.docx 文件,我会得到 наÑалÑÑ.pdf。

完整的响应头

Pragma: no-cache 
Transfer-Encoding: chunked 
Access-Control-Allow-Origin: * 
Result: True 
StoreFile: false 
Timeout: 300 
OutputFileName: наÑалÑÑ.pdf 
Content-Disposition: attachment; filename=наÑалÑÑ.pdf 
Cache-Control: no-cache, no-store 
Content-Type: application/pdf 
Date: Wed, 12 Sep 2012 07:21:37 GMT 
Expires: -1 
Server: Microsoft-IIS/7.5 
X-AspNet-Version: 4 

我正在读取这样的 header 值

HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postdatatoserver); 
using (Stream clientResponse = webResponse.GetResponseStream()) 
if (webResponse.StatusCode == HttpStatusCode.OK) 
{ 
   Helpers.CopyStream(clientResponse, outStream); 
   webHeaderCollection = webResponse.Headers; 
} 

我不确定当我从响应头中读取乱序字符时我应该只将它们解码为 un​​icode 还是当我从 Web API 服务器发送数据时我需要将编码包含到响应头中?

请您参考如下方法:

参见 http://msdn.microsoft.com/en-us/library/system.net.webresponse.getresponsestream.aspx :

Stream ReceiveStream = myWebResponse.GetResponseStream(); 
Encoding enc = System.Text.Encoding.UTF8; 
 
// Pipe the stream to a higher level stream reader with the required encoding format.  
StreamReader readStream = new StreamReader(ReceiveStream, enc); 

你也可以试试

System.Text.Encoding.Default 
or 
System.Text.Encoding.UTF7 
or 
System.Text.Encoding.Unicode 
or  
System.Text.Encoding.GetEncoding(1251) 
or  
System.Text.Encoding.GetEncoding(1252) 
or 
System.Text.Encoding.GetEncoding(20866) 

查看此处以获得更长的列表:
http://www.pcreview.co.uk/forums/system-text-encoding-getencoding-whatvalidstrings-t1406242.html

编辑:

Current [RFC 2045] grammar restricts parameter values (and hence Content-Disposition filenames) to US-ASCII.

因此无论 StreamReader 编码如何,HTTP header 始终以 ASCII 格式传输。
IE不符合标准,所以有一个解决方法:UrlEncode the filename

所以在回写文件的时候需要这样做:

// IE needs url encoding, FF doesn't support it, Google Chrome doesn't care 
if (Request.Browser.IsBrowser ("IE")) 
{ 
    fileName = Server.UrlEncode(fileName); 
} 
 
Response.Clear (); 
Response.AddHeader ("content-disposition", String.Format ("attachment;filename=\"{0}\"", fileName)); 
Response.AddHeader ("Content-Length", data.Length.ToString (CultureInfo.InvariantCulture)); 
Response.ContentType = mimeType; 
Response.BinaryWrite(data); 

根据 Unicode in Content-Disposition header 您可以添加一个星号,并附加正确的编码。