HttpRequestMessage/StreamContent,服务器端的空 Stream

本文关键字:Stream 服务器端 StreamContent HttpRequestMessage | 更新日期: 2023-09-27 18:32:29

我想将流发布到 HTTP 服务器(由 OWINHost 托管),请参阅下面的代码片段。当我使用字符串内容传输字符串时,它工作正常。但是,如果我想使用 StreamContent 传输 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!");
    });
  }
}

HttpRequestMessage/StreamContent,服务器端的空 Stream

我忘了包括:

stream.Seek(0, SeekOrigin.Begin);

在客户端。