Check null for HttpWebResponse

2019-03-31 12:08发布

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)));
}

标签: c# wcf http rest
3条回答
我命由我不由天
2楼-- · 2019-03-31 12:53

No built-in type derived from WebResponse, in particular HttpWebResponse, can return null. This superstitious belief has misled many developers. Don't check for null. Such code is dead code.

What would null even mean compared to returning an empty stream?! This does not make sense.

Also, GetResponse() cannot return null. Again, what is that supposed to mean?! The HTTP protocol does not support the notion of a "null response". If that ever happens due to a library bug it's not possible to handle that situation anyway. Any such check does not help.

It is possible to create classes derived from WebResponse that return an insane values such as null. No built-in class does that and it should be considered a bug to return null. Classes derived from WebResponse are very rare. I have never seen one.

Here's a good code pattern to use:

var request = WebRequest.Create("http://example.org/");

using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var responseReader = new StreamReader(responseStream))
{
    var contents = responseReader.ReadToEnd();
}

It demonstrates how to succinctly and safely read the contents of an HTTP URL using HttpWebRequest.

查看更多
Rolldiameter
3楼-- · 2019-03-31 12:53

You are not right. C# Forms:

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);

My first web request passes normally, the second returns null. I do not even know where the error is. It is clear that it is in the code. And the C# code has its own bugs too.

myRequestState.response.Close(); //myRequestState.response==null !!!

You do not consider headings, multithreading etc., etc. I advise you to try to write the web handler yourself and return null from server. Finnaly null was in

sysnem.threeding.nManualResetEvent allDone

It was necessary to add:

allDone.Reset();

enter code here

查看更多
beautiful°
4楼-- · 2019-03-31 13:01

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.

查看更多
登录 后发表回答