Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# HttpRequestMessage/StreamContent,服务器端的空流_C#_Asp.net_Owin - Fatal编程技术网

C# HttpRequestMessage/StreamContent,服务器端的空流

C# HttpRequestMessage/StreamContent,服务器端的空流,c#,asp.net,owin,C#,Asp.net,Owin,我想将一个流发布到HTTP服务器(由OWINHost托管),请参阅下面的代码片段。 当我传输带有StringContent的字符串时,它可以正常工作。 但是,如果我想传输带有StreamContent的MemoryStream,则在服务器端接收的流是空的(为了测试目的,我在客户端对MemoryStream进行反序列化,以验证它是否正确)。 我做错了什么 客户端: ... var request = new HttpRequestMessage(HttpMethod.Post, Configura

我想将一个流发布到HTTP服务器(由OWINHost托管),请参阅下面的代码片段。 当我传输带有StringContent的字符串时,它可以正常工作。 但是,如果我想传输带有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!");
    });
  }
}
我忘了包括:

stream.Seek(0, SeekOrigin.Begin);

在客户端。

您是否已经向流中写入了一些内容?我在第一段代码中没有看到这种情况,但也许您已经这样做了。只是检查一下。是的,我确实在流中写入了一个对象。正如我所说,出于测试目的,我在客户端对流进行了反序列化,并恢复了对象。为了清晰起见,我省略了代码。我使用的是Windows 7和Microsoft.Owin和OwinHost 3.0,它在Visual Studio Express 2013中以调试模式运行,看起来您的操作是正确的。也许试着找出你的数据流的字节丢失在哪里。这可以通过WireShark来完成,WireShark是一个低级网络协议分析器。您可以看到发送的数据包是否包含流数据。WireShark是免费的,但不是初学者。