Use cookies from CookieContainer in WebBrowser

前端 未结 3 552
醉话见心
醉话见心 2020-11-30 05:07

Is there any way that I can actually use the cookies from a cookie container (taken from a WebRequest previously) and use them in a WebBrowser control? If so, how would I do

3条回答
  •  醉梦人生
    2020-11-30 05:52

    Try to first use "client" CookedWebClient for the first navitation and get all the cookies from server. Then you can take the CookedContainer from CookedWebClient, or some other source like WebRequest, and use them in WebBrowser as shown below:

    namespace ExampleWebBrowser
    {
        public partial class Form1 : Form
        {
             [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
             public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);
    
             CookedWebClient client = new CookedWebClient();
    
             ..
             ..
             ..
    
             private void usingWebBrowserWithWebClientCookies(string url)
             {
                CookieCollection cookies = client.Cookies.GetCookies(url);
                for (int i = 0; i < cookies.Count; i++)
                {
                   Cookie c = cookies[i];
                   InternetSetCookie(url, c.Name, c.Value);
                }
                webBrowser1.Navigate(url);
             }
         }
    
         public class CookedWebClient : WebClient
         {
            CookieContainer cookies = new CookieContainer();
            public CookieContainer Cookies { get { return cookies; } }
            protected override WebRequest GetWebRequest(Uri address)
            {
               WebRequest request = base.GetWebRequest(address);
               if (request.GetType() == typeof(HttpWebRequest))
                  ((HttpWebRequest)request).CookieContainer = cookies;
               return request;
            }
         }
    }
    

提交回复
热议问题