HttpRequestMessage / StreamContent, server-side empty stream

I want to publish a stream to an HTTP server (hosted by OWINHost), see the code snippet below. It works fine when I transfer String with StringContent. However, if I want to transfer a MemoryStream with a StreamContent, the stream received on the server side is empty (I checked that the MemoryStream is correct by deserializing it on the client side for testing purposes). What am I doing wrong?

on the 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!"); }); } } 
+5
source share
1 answer

I forgot to include:

 stream.Seek(0, SeekOrigin.Begin); 

on the client side.

+4
source

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


All Articles