HttpClient内容处置中的编码错误 [英] HttpClient wrong encoding in Content-Disposition
问题描述
我正在使用 HttpClient
发布图像,它对于带有拉丁名称的文件效果很好,但是一旦名称包含任何非ASCII字符,它将立即转换为问号序列.如果我创建一个html表单并使用浏览器发布该文件,则该文件名将以UTF8发送,并且目标服务器会完全接受它.
I am POST-ing an image with HttpClient
and it works well for files with Latin names, but as soon as a name contains any non-ASCII characters it gets transformed to a sequence of question marks. If I create an html form and use a browser to post the file, the file name is sent in UTF8 and the target server perfectly accepts it.
using (var client = new HttpClient())
{
var streamContent = new StreamContent(someImageFileStream);
streamContent.Headers.Add(
"Content-Disposition",
"form-data; name=\"image\"; filename=\"Тест.jpg\"");
var content = new MultipartFormDataContent();
content.Add(streamContent);
await client.PostAsync("http://localhost.fiddler/", content);
}
这将产生以下请求:
POST http://localhost/ HTTP/1.1
Content-Type: multipart/form-data; boundary="e6fe89be-e652-4fe3-8859-8c7a339c5550"
Host: localhost
Content-Length: 10556
--e6fe89be-e652-4fe3-8859-8c7a339c5550
Content-Disposition: form-data; name="image"; filename="????.jpg"
...here goes the contents of the file...
我了解 HttpClient
可以按照某些标准工作,但是无论如何,有什么解决方法吗?
I understand that HttpClient
might work according to some standard, but anyway, is there any workaround?
更新:外部API不想接受 filename * =utf-8''Тест.jpg
格式,它需要 filename ="Тест.jpg"
.
UPDATE: The external API doesn't want to accept the format filename*=utf-8''Тест.jpg
, it expects filename="Тест.jpg"
.
推荐答案
好的,我找到了一种方法来强制 MultipartFormDataContent
忘记古老的RFC,而改用UTF8.诀窍是使用反射来覆盖内部静态类 HttpRuleParser
中定义的 DefaultHttpEncoding
.
OK, I've found a way to force MultipartFormDataContent
to forget the ancient RFCs and use UTF8 instead. The trick is to use reflection to overwrite the DefaultHttpEncoding
defined in the internal static class HttpRuleParser
.
typeof(HttpClient)
.Assembly
.GetType("System.Net.Http.HttpRuleParser")
.GetField("DefaultHttpEncoding", BindingFlags.Static | BindingFlags.NonPublic)
.SetValue(null, System.Text.Encoding.UTF8);
不确定会导致哪些不良后果,但我想没有.
Not sure which bad consequences that might cause, but I suppose there are none.
这篇关于HttpClient内容处置中的编码错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!