HttpRequestMessage / StreamContent,服务器端的空流

时间:2014-11-29 13:34:05

标签: c# asp.net owin

我想将流发布到HTTP服务器(由OWINHost托管),请参阅下面的代码段。 当我使用StringContent传输String时,它工作正常。 但是,如果我想使用StreamContent传输MemoryStream,则服务器端收到的流为空(我通过在客户端对其进行反序列化以进行测试来验证MemoryStream是否正确)。 我做错了什么?

客户端:

...
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);
...

服务器端:

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!");
    });
  }
}

1 个答案:

答案 0 :(得分:5)

我忘了包括:

stream.Seek(0, SeekOrigin.Begin);

在客户端。