我开发了web api,它使用POST方法接受文件,进行操作并使用HTTP Response返回它们。 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;
}
我不确定当我从响应头读取它们时,我应该只将scrambled字符解码为unicode,或者当我从web api服务器发送数据时,我需要将编码包含在响应头中吗?
答案 0 :(得分: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-Header始终以ASCII格式传输 IE不符合标准,因此有一种解决方法:UrlEncode文件名
所以你需要在写回文件时这样做:
// 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 你可以添加一个星号,并附加正确的编码。