最佳答案
我以前在 HttpWebRequest 和 HttpWebResponse 会话中使用过 CookieContainer,但是现在,我想在 WebClient 中使用它。据我所知,没有像 HttpWebRequest (request.CookieContainer
)那样的内置方法。如何从 CookieContainer 中的 WebClient 收集 Cookie?
public class CookieAwareWebClient : WebClient
{
private readonly CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
HttpWebRequest webRequest = request as HttpWebRequest;
if (webRequest != null)
{
webRequest.CookieContainer = m_container;
}
return request;
}
}
这是最好的办法吗?