我有以下代码,它重新使用在第一个请求时登录的 CookieContainer,但之后只使用 cookie 容器进行请求。
一段时间后,如果站点空闲,则会出现会话超时,我将需要再次执行登录。
问:我能否确定(使用 cookie 容器对象)是否发生超时,或者最好从 HttpWebResponse 中确定它是否发生,该 HttpWebResponse 恰好包含“会话超时”之类的文本。做这个的最好方式是什么?
private static CookieContainer _cookieContainer;
private static CookieContainer CurrentCookieContainer
{
get
{
if (_cookieContainer == null || _cookieContainer.Count == 0)
{
lock (_lock)
{
if (_cookieContainer == null || _cookieContainer.Count == 0)
{
//_cookieContainer.GetCookies(
_cookieContainer = DoLogin();
}
}
}
return _cookieContainer;
}
set
{
_cookieContainer = value;
}
}
然后这个方法调用容器:
public static string SomeMethod(SomeParams p)
{
HttpWebRequest request_thirdPartyEnquiryDetails = (HttpWebRequest)WebRequest.Create(thirdPartyEnquiryDetails);
CookieContainer cookieContainer = CurrentCookieContainer;
request_thirdPartyEnquiryDetails.CookieContainer = cookieContainer;
//... and it goes on to submit a search and return the response
}