1

我想将字符串参数和文件发送到网络服务器。我的 streamContent 出错 这是我的代码

using (var client = new HttpClient())
{
  using (var content = new MultipartFormDataContent())
  {
   content.Add(new StringContent("loginTest"), "login");
   content.Add(new StringContent("toto"), "username");
   using (fileStream = new FileStream("C:\\test.pdf", FileMode.Open, 
          FileAccess.Read, FileShare.Read, 4096, useAsync: true))
    {
     var filestreamContent = new StreamContent(fileStream, 4096);
     content.Add(filestreamContent, "documentUpload", "test.pdf");

     using (var message = client.PostAsync("http://serverUrl/Create? 
      method=init", content))
     {
      var input = message.Result.Content.ReadAsStringAsync().Result;
      }
    }
   }
 }

这是一个错误的屏幕截图:System.ObjectDisposedException https://i.imgur.com/IHspYbB.jpg

4

2 回答 2

1

当将 fileStream 作为参数传递给 StreamContent 的构造函数时,它获取所有权。即在处理filestreamContent 时,它也会处理fileStream。将 filestreamContent 添加到内容时,它也具有所有权,即在处理内容时,它将遍历所有部分,然后也处理这些部分。

而 HttpClient.PostAsync 最终会调用私有函数 HttpClient.DisposeRequestContent,后者依次处理内容,内容将关闭并处理所有关联的流。这是设计使然。

您只是看到了最终结果,据我所知,除了尝试访问调试器中现在处理的对象的成员时,您没有收到任何错误或异常。

于 2019-01-28T16:29:27.807 回答
0

你可以用这个。

using (var httpClient = new HttpClient())
  {
   MemoryStream img = new MemoryStream();
   imgFile.InputStream.CopyTo(img1);
   img1.Seek(0, SeekOrigin.Begin);
   Dictionary<string, string> parameters = new Dictionary<string, string>();

   parameters.Add("Token", model.Token);
   parameters.Add("Phone", model.Phone);
   parameters.Add("FullName", model.FullName);
   
                  
   using (var content = new MultipartFormDataContent())
     {
      content.Add(new StreamContent(img1), "Image", "Image." + Path.GetExtension(national.FileName));
      HttpContent dictionaryItems = new FormUrlEncodedContent(parameters);
      content.Add(dictionaryItems, "AuthenticationViewModel");
                       
      var url = "mysite/api/People/InsertInfo";

      var response = await httpClient.PostAsync(url, content);
      var responseModel =
      JsonConvert.DeserializeObject<ResponseModel>(
                                (await response.Content.ReadAsStringAsync()));
     if (responseModel.IsSuccess)
                            return Json(new { IsSuccess = true }, JsonRequestBehavior.AllowGet);
     }

    }

在阿皮

 var request = HttpContext.Current.Request;
 bool files = (request.Files.Count != 0);

 string data = request.Form.GetValues("AuthenticationViewModel").First();
 NameValueCollection model = HttpUtility.ParseQueryString(data);
 var token = model.GetValues("Token").First()
于 2021-10-06T11:21:30.097 回答