检查HttpWebResponse的null [英] Check null for HttpWebResponse
问题描述
我正在向REST服务发出HTTP post请求,当我收到HttpWebResponse时,我正在检查下面。当我正在做webresponse时,我还应该检查responseStream!= null!= null
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)));
}
推荐答案
HttpWebResponse.GetResponseStream()
可以返回null,所以是的,你应该检查它是否为空。
HttpWebResponse.GetResponseStream()
can return null, so yes, you should check whether it is null or not.
你还应该检查是否 HttpWebResponse.GetResponseStream()== Stream.Null
所以,像这样:
var webResponseStream = webResponse.GetResponseStream();
if (webResponseStream != null && webResponseStream != Stream.Null)
{
//do stuff.
}
如果您想知道, webResponseStream!= null
检查是否已将对Stream的引用分配给变量 webResponseStream
,而 webResponseStream!= Stream.Null
检查分配给 webResponseStream
的Stream实例是否包含任何后备数据。
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.
这篇关于检查HttpWebResponse的null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!