c# – 可以在“using”语句中为Web请求嵌入“try / catch”吗?我的代码是否正确?

前端之家收集整理的这篇文章主要介绍了c# – 可以在“using”语句中为Web请求嵌入“try / catch”吗?我的代码是否正确?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以在“using”语句中为Web请求嵌入“try / catch”?我的代码是否正确?那是我的要求是:

>想要使用“using”语句来确保在任何情况下都为HttpWebResponse释放资源

>但是如果有异常重新获取HttpWebResponse和“response =(HttpWebResponse)request.GetResponse();”仍然想做一些自定义的东西.特别是.

我的源代码

var result = new HttpHeaderInfo();
        HttpWebRequest request = null;
        HttpWebResponse response = null;
        using (response)
        {
            try
            {
                request = (HttpWebRequest)WebRequest.Create(uri);
                request.Method = "HEAD";
                request.KeepAlive = false;
                request.Timeout = Properties.Settings.Default.WebTimeoutDefault;

                response = (HttpWebResponse)request.GetResponse();
                result.LastModified = response.LastModified;
                result.ContentType = response.ContentType;
                result.StatusCode = response.StatusCode;
                result.ContentLength = response.ContentLength;
            }
            catch (Exception ex)
            {
                if (ex is InvalidOperationException ||
                    ex is ProtocolViolationException ||
                    ex is WebException)
                {
                    result.HttpError = ex;
                    result.LastModified = System.DateTime.MinValue;
                    result.ContentType = null;
                }
                else { throw; }
            }

        }

谢谢

解决方法

没关系,但有点多余;在一般意义上,您可以轻松地删除using块,在catch之后添加finally块,并在那里显式调用Dispose,这将减少代码中的嵌套.

在更具体的意义上,让我感到困惑的是,在进入using块之前,实际上并没有分配响应,并且显式变量声明在此上下文中是不必要的并且令人困惑.我会把它重写为:

HttpHeaderInfo result;
try
{
    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "HEAD";
    request.KeepAlive = false;
    request.Timeout = Properties.Settings.Default.WebTimeoutDefault;

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        result = new HttpHeaderInfo();
        result.LastModified = response.LastModified;
        result.ContentType = response.ContentType;
        result.StatusCode = response.StatusCode;
        result.ContentLength = response.ContentLength;
    }
}
catch (WebException ex)
{
    // etc.
}

这比原始形式更清晰.另请注意,我正在捕获WebException,而不是通用的System.Exception.您应该捕获特定的异常类型,而不是捕获一般异常,然后检查它们的类型.

猜你在找的C#相关文章