I want to post a stream to a HTTP server (hosted by OWINHost), see code snippet below. It works fine when I transfer a String with StringContent. However if I want to transfer a MemoryStream with StreamContent, the stream received on the server side is empty (I verified that the MemoryStream is correct by deserializing it on client side for test purposes). What am I doing wrong?
Client-side:
...
var request = new HttpRequestMessage(HttpMethod.Post, Configuration.ServiceBaseAddress);
// this works fine!
//request.Content = new StringContent("This is a test!!");
request.Content = new StreamContent(stream);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
HttpResponseMessage response = await client.SendAsync(request);
...
Server-side:
public class Startup {
public void Configuration(IAppBuilder app) {
app.Run(async context =>
{
var stream = new MemoryStream();
await context.Request.Body.CopyToAsync(stream);
stream.Seek(0, SeekOrigin.Begin);
// this works fine when I send StringContent
//StreamReader reader = new StreamReader(stream);
//String str = reader.ReadToEnd();
// when I send StreamContent the stream object is empty
IFormatter formatter = new BinaryFormatter();
ServiceRequest requestTest = (ServiceRequest)formatter.Deserialize(stream);
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync("Hello World!");
});
}
}
I forgot to include:
stream.Seek(0, SeekOrigin.Begin);
on the client-side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With