在我的MVC视图中循环浏览网址列表
@foreach (var item in Model)
{
HttpWebRequest webRequest = HttpWebRequest.Create(@item.URL) as HttpWebRequest;
webRequest.Method = WebRequestMethods.Http.Get;
webRequest.ContentType = "application/x-www-form-urlencoded";
using (HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.OK)
{
//do something
}
else
{
//Move to the next record
}
}
}
我正在做的事情很好但是当发生错误时它无法移动到下一条记录。
我收到服务器错误无法解析远程名称:后跟循环中的网址。
谢谢, 道格
答案 0 :(得分:0)
请务必阅读文档:GetResponse
类的HttpWebRequest
方法可以抛出WebException
,这就是您所获得的。基本上,您的代码永远不会到达下一条记录,因为它在此之前抛出了未处理的异常。
代码的最后一部分应该更像:
HttpWebResponse response = null;
try
{
response = webRequest.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
{
//do something
}
}
catch (WebException ex) { }
finally
{
if (response != null) response.Dispose();
}