Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpRequestMessage/StreamContent, empty Stream on server side

Tags:

c#

asp.net

owin

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!");
    });
  }
}
like image 909
matt77 Avatar asked Nov 29 '14 13:11

matt77


1 Answers

I forgot to include:

stream.Seek(0, SeekOrigin.Begin);

on the client-side.

like image 90
matt77 Avatar answered Oct 11 '22 22:10

matt77