Example #1
0
        protected override WebRequest GetWebRequest(Uri address)
        {
            // The only way to get the method is to call base.GetWebRequest() and copy its properties.
            // Note that calling this method also clears most headers from the WebClient.

            WebRequest baseWebRequest = base.GetWebRequest(address);

            if (baseWebRequest is HttpWebRequest baseHttpWebRequest)
            {
                IHttpWebRequest httpWebRequest = webRequestFactory.Create(address);

                if (baseHttpWebRequest.Credentials is object)
                {
                    httpWebRequest.Credentials = baseHttpWebRequest.Credentials;
                }

                httpWebRequest.Method = baseHttpWebRequest.Method;

                if (!(baseHttpWebRequest.Proxy is PlaceholderWebProxy))
                {
                    httpWebRequest.Proxy = baseHttpWebRequest.Proxy;
                }

                httpWebRequest.WithHeaders(baseHttpWebRequest.Headers);

                return(httpWebRequest as WebRequest);
            }
            else
            {
                return(baseWebRequest);
            }
        }
Example #2
0
        public static IHttpWebRequest WithOptions(this IHttpWebRequest httpWebRequest, IHttpWebRequestOptions options, bool copyIfNull = true)
        {
            if (copyIfNull || !string.IsNullOrWhiteSpace(options.Accept))
            {
                httpWebRequest.Accept = options.Accept;
            }

            if (copyIfNull || !string.IsNullOrWhiteSpace(options.AcceptLanguage))
            {
                httpWebRequest.Headers[HttpRequestHeader.AcceptLanguage] = options.AcceptLanguage;
            }

            if (copyIfNull || options.AllowAutoRedirect.HasValue)
            {
                httpWebRequest.AllowAutoRedirect = options.AllowAutoRedirect ?? httpWebRequest.AllowAutoRedirect;
            }

            httpWebRequest.AutomaticDecompression = options.AutomaticDecompression;

            if (copyIfNull || options.Cookies is object)
            {
                httpWebRequest.CookieContainer = options.Cookies;
            }

            if (copyIfNull || options.Credentials is object)
            {
                httpWebRequest.Credentials = options.Credentials;
            }

            if (httpWebRequest.Headers is object && options.Headers is object)
            {
                httpWebRequest.WithHeaders(options.Headers);
            }

            if (copyIfNull || options.Proxy is object)
            {
                httpWebRequest.Proxy = options.Proxy;
            }

            if (copyIfNull || !string.IsNullOrWhiteSpace(options.UserAgent))
            {
                httpWebRequest.UserAgent = options.UserAgent;
            }

            return(httpWebRequest);
        }