You can make the solution a bit more tidy by creating a new "wrapper" HttpContent class that allows your content class to be re-used. When sending content, HttpClient automatically disposes any request content, "just in case". This isn't idea for your case. Fortunately, the Dispose(bool) method is virtual, so you can override the dispose behaviour in derived class.
public class ReusableContent : HttpContent
{
private readonly HttpContent _innerContent;
public ReusableContent(HttpContent innerContent)
{
_innerContent = innerContent;
}
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
await _innerContent.CopyToAsync(stream);
}
protected override bool TryComputeLength(out long length)
{
length = -1;
return false;
}
protected override void Dispose(bool disposing)
{
// Don't call base dispose
//base.Dispose(disposing);
}
}
Once you have this class, you can use it like this,
[Fact]
public async Task Sending_same_content_multiple_times()
{
var client = new HttpClient { BaseAddress = _BaseAddress };
var stream = new MemoryStream();
var sw = new StreamWriter(stream);
sw.Write("This is a stream");
sw.Flush();
stream.Position = 0;
var multipart = new MultipartContent
{
new StringContent("This string will be sent repeatedly"),
new FormUrlEncodedContent(new[] {new KeyValuePair<string, string>("foo", "bar"),}),
new StreamContent(stream)
};
var content = new ReusableContent(multipart);
for (int i = 0; i < 10; i++)
{
var response = await client.PostAsync("devnull", content);
response.EnsureSuccessStatusCode();
}
}
If you do use this, make sure you don't use an content that does actually need to be disposed without disposing of it manually.