System.Net.HttpWebResponse Returns System.IO.Stream.NullStream

I have a case where HttpWebResponse.GetResponseStream() returns a System.Net.NullStream , although checking the HttpWebResponse object shows that its base m_ConnectStream is an instance of System.Net.ConnectStream , and the ContentLength property matches exactly the length of the content returned from the server. I also poked in the "Clock" window and found my data, but I can’t remember where I found it, but I KNOW that I have answer data, the execution time simply will not allow me!

The only thing that differs from other successful scripts is that the verb HttpWebRequest is "HEAD". I am implementing a RESTful web service and want to use "HEAD" to request metadata for resources.

+4
source share
1 answer

It revealed:

The following .Net Fx source code was found (in the HttpWebResponse class):

 /// <devdoc> /// <para>Gets the stream used for reading the body of the response from the /// server.</para> /// </devdoc> public override Stream GetResponseStream() { if (Logging.On) Logging.Enter(Logging.Web, this, "GetResponseStream", ""); CheckDisposed(); if (!CanGetResponseStream()) { // give a blank stream in the HEAD case, which = 0 bytes of data if (Logging.On) Logging.Exit(Logging.Web, this, "GetResponseStream", Stream.Null); return Stream.Null; } if (Logging.On) Logging.PrintInfo(Logging.Web, "ContentLength=" + m_ContentLength); if (Logging.On) Logging.Exit(Logging.Web, this, "GetResponseStream", m_ConnectStream); return m_ConnectStream; } 

As you can see, it explicitly returns an empty stream for "HEAD" requests. "Why do this?" I'm asking.

I found this at http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html :

9.4 HEAD

The HEAD method is identical to GET, except that the server SHOULD NOT return the message body in response. The metadata contained in the HTTP headers in response to the HEAD request MUST be identical to the information sent in response to the GET request. This method can be used to obtain meta-information about the entity implied by the request, without transferring the object-object itself. This method is often used to check for hypertext links for authenticity, accessibility, and recent modification.

Wow. I took from the book of Richardson and Ruby RESTful Web Services that you can be smart and respond to a "HEAD" request with an empty XHTML form that would fully describe the structure of resource elements, including mandatory, data type, length, etc. Using all attributes of the XHTML form field (5). However, after reading the HTTP specification, it is clear that all the "HEAD" response data must go into the HTTP headers.

Well, you learn something new every day ...

+2
source

All Articles