2

我开发了 web api,它使用 POST 方法接受文件,进行操作并使用 HTTP 响应返回它们。Web api 在 http 标头中返回附加数据,例如输出文件名。问题是,然后我使用 HttpWebResponse 发布和接收响应我在响应标头值中得到了乱码文件名,并且 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

我正在阅读这样的标题值

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 服务器发送数据时我可能需要将编码包含到响应标头中?

4

1 回答 1

0

请参阅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

编辑:

当前 [RFC 2045] 语法将参数值(以及因此的 Content-Disposition 文件名)限制为 US-ASCII。

因此,无论 StreamReader 编码如何,HTTP 标头始终以 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);

根据 Content-Disposition 标头中的 Unicode, 您可以添加星号,并附加正确的编码。

于 2012-09-12T09:24:30.220 回答