客户端使用MultipartFormDataContent和两部分数据,一个是文件,另一个是一些元数据。 在每3个请求中,由于FileData为空,将有2个请求失败。
客户端:
var client = new HttpClient(new WebRequestHandler());
using (var content = new MultipartFormDataContent())
{
var guid = Guid.NewGuid().ToString();
var tmpFileName = string.Format("{0}{1}", guid, Path.GetExtension(fileName));
var dataContent = new ByteArrayContent(data);
content.Add(dataContent, guid, tmpFileName);
var optionContent = new ByteArrayContent(optionData);
optionContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("parameter") { Name = "optionsStr" };
content.Add(optionContent);
var response = client.PostAsync("http://test.com", content).Result;
}
服务器:
[HttpPost]
public async Task<HttpResponseMessage> UploadDocument(string dataStr)
{
string rootPath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Documents");
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(rootPath);
await Request.Content.ReadAsMultipartAsync(provider);
if (provider.FileData == null || provider.FileData.Count == 0)
throw new Exception("There is no file in the current request of httpcontext.");
}
使用Wiresharks嗅探后,发现实际文件数据在多部分结构的前导码部分放错位置:
错误请求:
正确的要求:
任何可能导致此类行为的线索?