C# 使用HttpWebRequest循环URL列表,导致错误
在我的MVC视图中循环浏览URL列表 @模型中的每个var项 { HttpWebRequest-webRequest=HttpWebRequest。Create@item.URL作为HttpWebRequest; webRequest.Method=WebRequestMethods.Http.Get; webRequest.ContentType=application/x-www-form-urlencoded; 使用HttpWebResponse=webRequest.GetResponse作为HttpWebResponse { 如果response.StatusCode==HttpStatusCode.OK { //做点什么 } 其他的 { //移动到下一个记录 } } } 我得到了做一些事情的罚款,但当一个错误发生时,它不能移动到下一个记录 我收到一个服务器错误,无法解析远程名称:后跟循环中的url 谢谢,C# 使用HttpWebRequest循环URL列表,导致错误,c#,asp.net-mvc-4,httpwebrequest,C#,Asp.net Mvc 4,Httpwebrequest,在我的MVC视图中循环浏览URL列表 @模型中的每个var项 { HttpWebRequest-webRequest=HttpWebRequest。Create@item.URL作为HttpWebRequest; webRequest.Method=WebRequestMethods.Http.Get; webRequest.ContentType=application/x-www-form-urlencoded; 使用HttpWebResponse=webRequest.GetRespons
Doug始终阅读文档:HttpWebRequest类的GetResponse方法可以抛出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();
}