user3456546 user3456546 - 2 months ago 22
HTTP Question

Check null for HttpWebResponse

I am making HTTP post request to REST service, When I get the HttpWebResponse back, I am doing below check. Should I also check responseStream != null when I am doing webresponse != null

HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
if (webResponse != null)
{
var responseStream = webResponse.GetResponseStream();
int responseCode = (int)webResponse.StatusCode;
if (responseStream != null && responseCode == (int)HttpStatusCode.Created)
{
cmsStoreWebResponse = ((new StreamReader(responseStream)).ReadToEnd());`
}
else
{
this.LogError(string.Format("{0}\n Endpoint: {1}\n {2} {3} {4}", ErrorCodes.IWS_CMSRetrieve_ERROR_001, oagEndpointUrl, ErrorCodes.IWS_CMSStore_ERROR_SERVICE_DOWN, responseStream, responseCode));
serviceData.Fatal = true;
serviceData.ErrorCode = ErrorCodes.IWS_EFORMSFORMSETS_001;
serviceData.ErrorDetails = string.Format("\nEndpoint: {0}\n {1}", oagEndpointUrl, ErrorCodes.RESPONSE_STREAM_NULL);
throw new FaultException<ServiceExceptionData>(serviceData, new FaultReason(string.Format("\nEndpoint: {0}\n {1}", oagEndpointUrl, ErrorCodes.RESPONSE_STREAM_NULL)));
}
}
else
{
this.LogError(string.Format("{0}\n Endpoint: {1}\n {2}", ErrorCodes.IWS_CMSRetrieve_ERROR_001, oagEndpointUrl, ErrorCodes.IWS_CMSStore_ERROR_SERVICE_DOWN));
serviceData.Fatal = true;
serviceData.ErrorCode = ErrorCodes.IWS_EFORMSFORMSETS_001;
serviceData.ErrorDetails = string.Format("\nEndpoint: {0}\n {1}", oagEndpointUrl, ErrorCodes.RESPONSE_STREAM_NULL);
throw new FaultException<ServiceExceptionData>(serviceData, new FaultReason(string.Format("\nEndpoint: {0}\n {1}", oagEndpointUrl, ErrorCodes.RESPONSE_STREAM_NULL)));
}

Answer

HttpWebResponse.GetResponseStream() can return null, so yes, you should check whether it is null or not.

You should also check whether HttpWebResponse.GetResponseStream() == Stream.Null

So, something like this:

var webResponseStream = webResponse.GetResponseStream();

if (webResponseStream != null && webResponseStream != Stream.Null)
{
    //do stuff.
}

In case you're wondering, webResponseStream != null checks for whether a reference to a Stream has been assigned to the variable webResponseStream, whereas webResponseStream != Stream.Null checks whether or not the Stream instance assigned to webResponseStream contains any backing data.