I've been able to read raw binary content from an HTTP API using this:
var response = httpClient.GetStreamAsync("http://...");
But how to do the same for writing?
So far, I've found no way to get an open Stream
to write asyncronously to the server.
The method HttpClient.PostAsync(...)
isn't useful for me, because it will take control over the read-write process to the server.
My goal is to have a Stream
to which I can write, like any other stream.
Is this even possible?
It is a little difficult to do what you want using the current API.
Depending on your requirement, you may want to just pass an existing stream. In which case use StreamContent
. Note that the stream needs to be filled (or otherwise fully readable) at the point the call is made. For example you can pass a FileStream
this way.
using var fs = new FileStream("someFile");
using var message = new HttpRequestMessage(HttpMethod.Post, "http://someurl.com");
message.Content = new StreamContent(fs);
using var resp = await _client.SendAsync(message);
// etc
This would be the easiest way to send most requests, as you normally have another stream you are sending.
If you want to be able to intercept the call to retrieve the stream and fill it then it's a bit more complicated. You need to create your own HttpContent
class, implementing at least the minimum overrides necessary. An example is given in the documentation for HttpContent
.