현재 원격으로 웹 서버에 요청하고 있습니다 (의도적으로).
요청 시간을 초과하는 가장 좋은 방법을 찾아야합니다. 기본적으로 요청이 "X"밀리 초보다 오래 실행되면 요청을 종료하고 null
응답을 반환합니다.
현재 웹 요청은 응답 대기 중입니다 .....
어떻게하면이 문제에 가장 잘 접근 할 수 있을까요?
다음은 현재 코드 스 니펫입니다.
public JsonpResult About(string HomePageUrl)
{
Models.Pocos.About about = null;
if (HomePageUrl.RemoteFileExists())
{
// Using the Html Agility Pack, we want to extract only the
// appropriate data from the remote page.
HtmlWeb hw = new HtmlWeb();
HtmlDocument doc = hw.Load(HomePageUrl);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@class='wrapper1-border']");
if (node != null)
{
about = new Models.Pocos.About { html = node.InnerHtml };
}
//todo: look into whether this else statement is necessary
else
{
about = null;
}
}
return this.Jsonp(about);
}
원래 게시 된 코드를 약간 수정해야했습니다.
public JsonpResult About(string HomePageUrl)
{
Models.Pocos.About about = null;
// ************* CHANGE HERE - added "timeout in milliseconds" to RemoteFileExists extension method.
if (HomePageUrl.RemoteFileExists(1000))
{
// Using the Html Agility Pack, we want to extract only the
// appropriate data from the remote page.
HtmlWeb hw = new HtmlWeb();
HtmlDocument doc = hw.Load(HomePageUrl);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//div[@class='wrapper1-border']");
if (node != null)
{
about = new Models.Pocos.About { html = node.InnerHtml };
}
//todo: look into whether this else statement is necessary
else
{
about = null;
}
}
return this.Jsonp(about);
}
그런 다음 RemoteFileExists
확장 메서드를 수정하여 시간 제한을 설정했습니다.
public static bool RemoteFileExists(this string url, int timeout)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// ************ ADDED HERE
// timeout the request after x milliseconds
request.Timeout = timeout;
// ************
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TRUE if the Status code == 200
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false.
return false;
}
}
이 접근법에서 RemoteFileExists
가 헤더 응답을 결정하기 전에 타임 아웃이 발생하면 내 bool
이 false를 반환합니다.
Html 민첩성 팩은 오픈 소스입니다. 왜 당신은 소스 yurself를 수정할 수 있습니다. 먼저이 코드를 HtmlWeb 클래스에 추가하십시오.
private int _timeout = 20000;
public int Timeout
{
get { return _timeout; }
set
{
if (_timeout < 1)
throw new ArgumentException("Timeout must be greater then zero.");
_timeout = value;
}
}
그런 다음이 방법을 찾으십시오.
private HttpStatusCode Get(Uri uri, string method, string path, HtmlDocument doc, IWebProxy proxy, ICredentials creds)
수정 :
req = WebRequest.Create(uri) as HttpWebRequest;
req.Method = method;
req.UserAgent = UserAgent;
req.Timeout = Timeout; //add this
또는 그런 것 :
htmlWeb.PreRequest = request =>
{
request.Timeout = 15000;
return true;
};