2
我刚刚注意到C#中的一些行为让我感到有些不适。我正在使用C#5和.NET 4.5。当我在一个HTTPResponse对象上调用GetResponseStream()时,我能够获得响应流,但是如果我在同一对象上再次调用它,则响应为空。我为什么只能调用GetResponseStream()一次
// Works! Body of the response is in the source variable.
HttpResponse response = (HttpWebResponse)request.GetResponse();
String source = new StreamReader(response.GetResponseStream()).ReadToEnd();
// Does Not Work. Source is empty;
String source2 = new StreamReader(response.GetResponseStream()).ReadToEnd();
以上只是一个示例来说明问题。
编辑
这就是我想要做的。基本上,如果一个事件附加到HTTP对象上,它会将响应传递回回调方法。
HttpWebResponse public Get(String url)
{
// HttpWebRequest ...
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// postRequest is an event handler. The response is passed to the
// callback to do whatever it needs to do.
if (this.postRequest != null)
{
RequestEventArgs requestArgs = new RequestEventArgs();
requestArgs.source = response;
postRequest.Invoke(this, requestArgs);
}
return response;
}
在回调方法中,我可能想检查响应的主体。如果是这样,当Get()返回响应时,我将丢失响应中的数据。
+1。请注意,其他[CanSeek](http://msdn.microsoft.com/en-us/library/system.io.stream.canseek.aspx)== == false流也是如此。 –
@SLaks如何制作响应流的副本?我将编辑我的问题,以增加我想要做的事情的一些清晰度。 –
@JamesJeffery:将它复制到MemoryStream – SLaks