I have a loop that is iterating through a short list of URIs
and needs to send each of them the same content. That HttpContent
resides in a variable passed into the call to PostAsync
. The problem I'm incurring is that the 1st call works perfectly, but all subsequent calls fail because the request content is null
after the 1st call completes.
I would assume my understanding of the PostAsync
call under the covers might be lacking some low level detail on the object and it's lifetime (or lack there of) so hopefully someone can shed some light on it for me.
The code looks as follows:
HttpResponseMessage httpResponseMessage = httpClient.PostAsync(destionationUri, messageContent).Result;
The variable in question is messageContent
which is of type MultipartFormDataContent
which derives from HttpContent
. I suppose some brute method of copying the value to a new and separate location for reuse might work, but I'm looking to understand why this happening and a proper method for allowing the content to persist during the loop.
Does anyone know how I can fix this issue, and upon looping around the code above, the messageContent
value will persist between iterations?
EDIT: I went ahead and refactored the code to rebuild the MultipartFormDataContent
from scratch using the same data prior to each call to PostAsync
using a new instance of HttpClient
. The call to rebuild the HtppContent
actually worked; the value is not null. However when I now go to make a subsequent call to PostAsync
and access .Result
I get the following error:
Error while copying content to a stream. Cannot access a closed Stream.
EDIT 2: Upon inspecting the 2nd call to my method to rebuild the MultipartFormDataContent
object from scratch, I notice that my attachment property when inspecting it's ContentStream
property (of a Mail.MailMessage
object) states the following:
attachment.ContentStream.Position threw an exception of type
System.ObjectDisposedException
All of the properties indicate the ContentStream
can no longer be read because it's disposed. The call to PostAsync().Result
apparently is disposing of the stream and is potentially the root issue. However I'm still unable to find a workable solution.