c# - 检查 HttpWebResponse 是否为空

标签 c# wcf http rest

我正在向 REST 服务发出 HTTP post 请求,当我返回 HttpWebResponse 时,我正在执行以下检查。当我做 webresponse != null 时,我是否也应该检查 responseStream != 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)));
}

最佳答案

WebResponse 派生的内置类型,特别是 HttpWebResponse,都不能返回 null。这种迷信的信念误导了许多开发人员。不要检查是否为空。这样的代码就是死代码。

与返回空流相比,null 甚至意味着什么?!这没有意义。

另外,GetResponse() 不能返回 null。 再说一次,那是什么意思?! HTTP 协议(protocol)不支持“空响应”的概念。如果由于库错误而发生这种情况,则无论如何都无法处理这种情况。任何此类检查都无济于事。

可以创建从 WebResponse 派生的类,返回一个疯狂的值,例如 null。没有内置类会这样做,返回 null 应该被视为错误。从 WebResponse 派生的类非常少见。我从未见过。

这里有一个很好用的代码模式:

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

它演示了如何使用 HttpWebRequest 简洁、安全地读取 HTTP URL 的内容。

关于c# - 检查 HttpWebResponse 是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22921555/

相关文章:

c# - 在 C# 中使用泛型 - 从泛型类调用泛型类

c# - log4net 通过异常参数将完整堆栈跟踪添加到数据库表

node.js - 为什么 Node.js 有 http.get 而没有 http.post?

http - 在哪里可以找到所有可能的 "Connection" header 值?

c# - 在 C# 中创建简单的嵌入式 http 和 https 应用程序

c# - LINQ:如何声明 IEnumerable[匿名类型]?

c# - 与我托管的 Windows 服务的安装程序一起,是否可以在发生错误时设置恢复选项?

单例模式下的WCF实例化,使用负载均衡器

c# - 使用 WCF 接收大对象

c# - 如何在启用 WCF silverlight 的服务中标记某些方法?