Using CookieContainer with WebClient class

后端 未结 5 2010
遇见更好的自我
遇见更好的自我 2020-11-22 02:07

I\'ve previously used a CookieContainer with HttpWebRequest and HttpWebResponse sessions, but now, I want to use it with a WebClient. As far as I understand, there is no bui

5条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 02:26

    I think there's cleaner way where you don't have to create a new webclient (and it'll work with 3rd party libraries as well)

    internal static class MyWebRequestCreator
    {
        private static IWebRequestCreate myCreator;
    
        public static IWebRequestCreate MyHttp
        {
            get
            {
                if (myCreator == null)
                {
                    myCreator = new MyHttpRequestCreator();
                }
                return myCreator;
            }
        }
    
        private class MyHttpRequestCreator : IWebRequestCreate
        {
            public WebRequest Create(Uri uri)
            {
                var req = System.Net.WebRequest.CreateHttp(uri);
                req.CookieContainer = new CookieContainer();
                return req;
            }
        }
    }
    

    Now all you have to do is opt in for which domains you want to use this:

        WebRequest.RegisterPrefix("http://example.com/", MyWebRequestCreator.MyHttp);
    

    That means ANY webrequest that goes to example.com will now use your custom webrequest creator, including the standard webclient. This approach means you don't have to touch all you code. You just call the register prefix once and be done with it. You can also register for "http" prefix to opt in for everything everywhere.

提交回复
热议问题