Object is located after PostAsync with HttpClient

I am trying to send a file with HttpClient, and if something on the recipient side fails, I want to resend the same file stream.

I am creating a mail request with MultipartFormDataContent that contains a stream. Everything looks fine when I first call PostAsync. But when I try to retry the request, I get a System.ObjectDisposedException.

My file stream is deleted after the first call to PostAsync ... Why is there a solution to my problem?

Here is a basic example of what I'm talking about.

public ActionResult Index() { var client = new HttpClient { BaseAddress = new Uri(Request.Url.AbsoluteUri) }; var fi = new FileInfo(@"c:\json.zip"); using (var stream = fi.OpenRead()) { var content = new MultipartFormDataContent(); var streamContent = new StreamContent(stream); streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { FileName = "\"File\"" }; content.Add(streamContent); var isSuccess = client.PostAsync("Home/Put", content). ContinueWith(x => x.Result.Content.ReadAsAsync<JsonResponse>().Result.Success).Result; //stream is already disposed if (!isSuccess) { isSuccess = client.PostAsync("Home/Put", content). ContinueWith(x => x.Result.Content.ReadAsAsync<JsonResponse>().Result.Success).Result; } } return View(); } public JsonResult Put(HttpPostedFileBase file) { return Json(new JsonResponse { Success = false }); } 
+6
source share
1 answer

If you call LoadIntoBufferAsync on a Content object, it copies the file stream to memystream inside the StreamContent object. Thus, removing HttpContent should not close FileStream. You will need to move the stream pointer and create a new StreamContent to make the second call.

0
source

Source: https://habr.com/ru/post/946501/


All Articles