可以在 Web 请求的“使用”语句中嵌入“尝试/捕获”吗?我的代码正确吗?那就是我的要求是:
想要使用“using”语句来确保在任何情况下都为 HttpWebResponse 释放资源
- 但是如果有异常 re 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; }
}
}
谢谢