c# – 检查HttpWebResponse的null

我正在向REST服务发出HTTP post请求,当我收到HttpWebResponse时,我正在进行下面的检查.当我在做webresponse时,我还应该检查responseStream!= null!= 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,所以是的,你应该检查它是否为null.

您还应该检查HttpWebResponse.GetResponseStream()== Stream.Null

所以,像这样:

var webResponseStream = webResponse.GetResponseStream();

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

如果你想知道,webResponseStream!=对于是否流的参考已经被分配给变量webResponseStream null检查,而webResponseStream!= Stream.Null检查分配给webResponseStream的流实例是否包含任何备份数据.

转载注明原文:c# – 检查HttpWebResponse的null - 代码日志