使用 Fiddler 调试后,将原始 http 消息与 WinMerge 进行比较,我发现 Firefox 和我的程序之间存在差异:
Firefox(删除了一些标题以使事情变得简单):
POST http://localhost:53400/Input/Upload HTTP/1.1
Host: localhost:53400
Content-Type: multipart/form-data; boundary=---------------------------1590871622043
Content-Length: ****
-----------------------------1590871622043
Content-Disposition: form-data; name="arg1"
abc
-----------------------------1590871622043
Content-Disposition: form-data; name="arg2"
3
-----------------------------1590871622043
Content-Disposition: form-data; name="uploadfile"; filename="wave.wav"
Content-Type: audio/wav
//file data here
-----------------------------1590871622043--
我的程序MultipartFormDataContent
:
POST http://localhost:53400/Input/Save HTTP/1.1
Content-Type: multipart/form-data; boundary="caac5ea7-8ab4-4682-be40-ecb3ddf3e70a"
Host: localhost:53400
Content-Length: ****
--caac5ea7-8ab4-4682-be40-ecb3ddf3e70a
Content-Disposition: form-data; name=arg1
abc
--caac5ea7-8ab4-4682-be40-ecb3ddf3e70a
Content-Disposition: form-data; name=arg2
3
--caac5ea7-8ab4-4682-be40-ecb3ddf3e70a
Content-Disposition: form-data; name=uploadfile; filename=wave.wav; filename*=utf-8''wave.wav
//file data here
--caac5ea7-8ab4-4682-be40-ecb3ddf3e70a--
我要注意的最后一件事是,在这些Content-Disposition
行中,Firefox 引用了所有值,但我的程序没有。人们可以很容易地认为这无关紧要,但最后,我发现这就是确切的原因。
现在我知道了原因,下面是可以工作的代码,就像引用名称一样简单:
var multipart = new MultipartFormDataContent();
multipart.Add(new StringContent("abc"), '"' + "arg1" + '"');
multipart.Add(new StringContent("3"), '"' + "arg2" + '"');
// byte[] fileData;
multipart.Add(new ByteArrayContent(fileData), '"' + "uploadfile"+ '"', '"' + "wave.wav" + '"');
//HttpClient http; string url;
var response = await http.PostAsync(url, multipart);
response.EnsureSuccessStatusCode();
//...