Exemplo n.º 1
0
        private void AddByAppendType(HttpRequestHeaders headers, string key, string value)
        {
            switch (_appendHeaderType)
            {
            case AppendHeaderType.Add:
                headers.TryAddWithoutValidation(key, value);
                break;

            case AppendHeaderType.AddIfNotExist:
                if (!headers.Contains(key))
                {
                    headers.TryAddWithoutValidation(key, value);
                }
                break;

            case AppendHeaderType.AddOrReplace:
                if (headers.Contains(key))
                {
                    headers.Remove(key);
                }
                headers.TryAddWithoutValidation(key, value);
                break;

            default:
                break;
            }
        }
Exemplo n.º 2
0
        public void AddInvalidAndValid()
        {
            HttpRequestMessage message = new HttpRequestMessage();
            HttpRequestHeaders headers = message.Headers;

            headers.TryAddWithoutValidation("User-Agent", "user,agent/1.0");
            headers.TryAddWithoutValidation("User-Agent", "agent2/2.0");

            Assert.AreEqual(1, headers.UserAgent.Count, "#1");
#if !__WATCHOS__
            if (HttpClientTestHelpers.UsingSocketsHandler)
#endif
            Assert.AreEqual("agent2/2.0 user,agent/1.0", headers.UserAgent.ToString(), "#2");
#if !__WATCHOS__
            else
            {
                Assert.AreEqual("agent2/2.0user,agent/1.0", headers.UserAgent.ToString(), "#2");
            }
#endif

            Assert.AreEqual("User-Agent: agent2/2.0 user,agent/1.0\r\n", headers.ToString(), "#3");

            headers.UserAgent.Clear();
            Assert.AreEqual("", headers.UserAgent.ToString(), "#4");
            Assert.AreEqual("", headers.ToString(), "#5");
        }
Exemplo n.º 3
0
        public void AddToHeaders(HttpRequestHeaders headers)
        {
            Guard.NotNull(headers, nameof(headers));

            if (IsFlatten)
            {
                headers.TryAddWithoutValidation("X-Flatten", "true");
            }

            if (IsUnpublished)
            {
                headers.TryAddWithoutValidation("X-Unpublished", "true");
            }

            if (Languages != null)
            {
                var languages = string.Join(", ", Languages.Where(x => !string.IsNullOrWhiteSpace(x)));

                if (!string.IsNullOrWhiteSpace(languages))
                {
                    headers.TryAddWithoutValidation("X-Languages", languages);
                }
            }

            if (AssetUrlsToResolve != null)
            {
                var assetFields = string.Join(", ", AssetUrlsToResolve.Where(x => !string.IsNullOrWhiteSpace(x)));

                if (!string.IsNullOrWhiteSpace(assetFields))
                {
                    headers.TryAddWithoutValidation("X-AssetFields", assetFields);
                }
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Allows the subclasses to add their own header information
 /// </summary>
 /// <param name="webHeaderCollection">The HTTP request headers</param>
 internal virtual void AddHeaders(HttpRequestHeaders webHeaderCollection)
 {
     if (!string.IsNullOrEmpty(this.AnchorMailbox))
     {
         webHeaderCollection.TryAddWithoutValidation(AnchorMailboxHeaderName, this.AnchorMailbox);
         webHeaderCollection.TryAddWithoutValidation(ExplicitLogonUserHeaderName, this.AnchorMailbox);
     }
 }
Exemplo n.º 5
0
 /// <summary>
 /// Sets authorization header.
 /// </summary>
 /// <param name="headers">The http request header.</param>
 /// <param name="value">The header value.</param>
 public static void SetAuthorization(this HttpRequestHeaders headers, string value)
 {
     if (!string.IsNullOrWhiteSpace(value))
     {
         headers.TryAddWithoutValidation("Authorization", value);
     }
 }
Exemplo n.º 6
0
 internal static void CopyTo(this HttpRequestHeaders from, HttpRequestHeaders to)
 {
     foreach (var header in from)
     {
         to.TryAddWithoutValidation(header.Key, header.Value);
     }
 }
Exemplo n.º 7
0
        public void Headers_Response()
        {
            HttpRequestMessage message = new HttpRequestMessage();
            HttpRequestHeaders headers = message.Headers;

            headers.Add("Age", "vv");
            Assert.AreEqual("vv", headers.GetValues("Age").First(), "#1");

            headers.Clear();
            headers.TryAddWithoutValidation("Age", "vv");
            Assert.AreEqual("vv", headers.GetValues("Age").First(), "#2");

            // .NET encloses the "Age: vv" with two whitespaces.
            var normalized = Regex.Replace(message.ToString(), @"\s", "");

#if !__WATCHOS__
            if (HttpClientTestHelpers.UsingSocketsHandler)
#endif
            Assert.AreEqual("Method:GET,RequestUri:'<null>',Version:2.0,Content:<null>,Headers:{Age:vv}", normalized, "#3");
#if !__WATCHOS__
            else
            {
                Assert.AreEqual("Method:GET,RequestUri:'<null>',Version:1.1,Content:<null>,Headers:{Age:vv}", normalized, "#3");
            }
#endif
        }
Exemplo n.º 8
0
 public static void AddHeaders(this HttpRequestHeaders container, params StringPair[] headers)
 {
     foreach (var header in headers)
     {
         container.TryAddWithoutValidation(header.Key, header.Value);
     }
 }
 public static void SetWithoutValidation(this HttpRequestHeaders headers, string name, string value)
 {
     if (headers.Contains(name))
     {
         headers.Remove(name);
     }
     headers.TryAddWithoutValidation(name, value);
 }
 /// <summary>
 /// Adds a header to the <see cref="HttpRequestHeaders"/> list object.
 /// </summary>
 /// <param name="headers">The request headers list object.</param>
 /// <param name="name">The name of the header to add.</param>
 /// <param name="value">The value of the header.</param>
 private static void AddHeader(HttpRequestHeaders headers, string name, string value)
 {
     if (headers.Contains(name))
     {
         headers.Remove(name);
     }
     headers.TryAddWithoutValidation(name, value);
 }
        protected virtual void AddDefaultHeaders(HttpRequestHeaders defaultHeaders)
        {
            defaultHeaders.Clear();
            defaultHeaders.ExpectContinue  = false;
            defaultHeaders.ConnectionClose = false;
            defaultHeaders.Add("Connection", "keep-alive");

            defaultHeaders.TryAddWithoutValidation("Content-type", "application/json; charset=utf-8");
            defaultHeaders.TryAddWithoutValidation("Accept-Charset", "utf-8");
            defaultHeaders.TryAddWithoutValidation("Accept", "application/json");
            defaultHeaders.TryAddWithoutValidation("Accept-Language", "pt-BR");

            if (this.ApiKey != null)
            {
                defaultHeaders.TryAddWithoutValidation("Authorization", string.Format("Bearer {0}", this.ApiKey));
            }
        }
Exemplo n.º 12
0
 public bool ProcessHeaders(HttpRequestHeaders requestHeaders)
 {
     if (headers.Any() && !headers.All(x => requestHeaders.TryAddWithoutValidation(x.Key, x.Value)))
     {
         throw new Exception("Headers could not be added.");
     }
     return(true);
 }
Exemplo n.º 13
0
        public void AddInvalidAndValid()
        {
            HttpRequestMessage message = new HttpRequestMessage();
            HttpRequestHeaders headers = message.Headers;

            headers.TryAddWithoutValidation("User-Agent", "user,agent/1.0");
            headers.TryAddWithoutValidation("User-Agent", "agent2/2.0");

            Assert.AreEqual(1, headers.UserAgent.Count, "#1");
            Assert.AreEqual("agent2/2.0user,agent/1.0", headers.UserAgent.ToString(), "#2");

            Assert.AreEqual("User-Agent: agent2/2.0 user,agent/1.0\r\n", headers.ToString(), "#3");

            headers.UserAgent.Clear();
            Assert.AreEqual("", headers.UserAgent.ToString(), "#4");
            Assert.AreEqual("", headers.ToString(), "#5");
        }
Exemplo n.º 14
0
 private static void CopyRequestHeaders(
     HttpRequestHeaders originalRequestHeaders,
     HttpRequestHeaders newRequestHeaders)
 {
     foreach (var header in originalRequestHeaders)
     {
         newRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
     }
 }
Exemplo n.º 15
0
		public static void UpdateRange(this HttpRequestHeaders requestHeaders, IEnumerable<KeyValuePair<string, string>> headers) {
			if (requestHeaders == null)
				throw new ArgumentNullException(nameof(requestHeaders));
			if (headers == null)
				throw new ArgumentNullException(nameof(headers));

			foreach (KeyValuePair<string, string> item in headers)
				requestHeaders.TryAddWithoutValidation(item.Key, item.Value);
		}
        protected virtual void ConfigureDefaultRequestHeaders(HttpRequestHeaders headers)
        {
            headers.Clear();
            headers.ConnectionClose = false;
            headers.TryAddWithoutValidation("Accept", "application/json");
            headers.TryAddWithoutValidation("Content-Type", "application/json");
            headers.CacheControl = new CacheControlHeaderValue
            {
                NoCache = true
            };

            if (CustomDefaultHttpHeaders != null)
            {
                foreach (var httpHeader in CustomDefaultHttpHeaders)
                {
                    headers.TryAddWithoutValidation(httpHeader.Key, httpHeader.Value);
                }
            }
        }
Exemplo n.º 17
0
        public static void CopyTo(this HttpRequestHeaders fromHeaders, HttpRequestHeaders toHeaders)
        {
            Contract.Assert(fromHeaders != null, "fromHeaders cannot be null.");
            Contract.Assert(toHeaders != null, "toHeaders cannot be null.");

            foreach (KeyValuePair <string, IEnumerable <string> > header in fromHeaders)
            {
                toHeaders.TryAddWithoutValidation(header.Key, header.Value);
            }
        }
Exemplo n.º 18
0
 private static void DictionaryHeaderConfiguration(HttpRequestHeaders requestHeaders, IReadOnlyDictionary <string, string> headers)
 {
     if (headers.Count == 0)
     {
         return;
     }
     foreach (var header in headers)
     {
         requestHeaders.TryAddWithoutValidation(header.Key, header.Value);
     }
 }
Exemplo n.º 19
0
 public static void AddHeaderValuesWithUploadInfo(HttpRequestHeaders headers, object info)
 {
     foreach (PropertyInfo propertyInfo in info.GetType().GetProperties())
     {
         HttpHeader attribute = propertyInfo.GetCustomAttribute <HttpHeader>();
         if (attribute != null)
         {
             headers.TryAddWithoutValidation(attribute.Name, propertyInfo.GetValue(info).ToString());
         }
     }
 }
Exemplo n.º 20
0
            public void OnHeader(ReadOnlySpan <byte> name, ReadOnlySpan <byte> value)
            {
                if (!HeaderDescriptor.TryGet(name, out HeaderDescriptor descriptor))
                {
                    throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_header_name, Encoding.ASCII.GetString(name)));
                }

                string headerValue = descriptor.GetHeaderValue(value);

                _headers.TryAddWithoutValidation(descriptor, headerValue.Split(',').Select(x => x.Trim()));
            }
Exemplo n.º 21
0
 /////////////////////////////////////////////////////////////
 /////////////////////////////////////////////////////////////
 ///////////////////////// INTERNALS /////////////////////////
 /////////////////////////////////////////////////////////////
 /////////////////////////////////////////////////////////////
 private static void TupleHeaderConfiguration(HttpRequestHeaders requestHeaders, IReadOnlyCollection <Tuple <string, string> > headers)
 {
     if (headers.Count == 0)
     {
         return;
     }
     foreach (var header in headers)
     {
         requestHeaders.TryAddWithoutValidation(header.Item1, header.Item2);
     }
 }
Exemplo n.º 22
0
 private void AddCommonAuthHeaders(HttpRequestHeaders headers, string referrer)
 {
     headers.Add("Accept-Language", "en-US,en;q=0.5");
     headers.Add("Connection", "keep-alive");
     headers.Add("Pragma", "no-cache");
     headers.Add("Cache-Control", "no-cache");
     headers.Host = "account.sonnen.de";
     if (!string.IsNullOrWhiteSpace(referrer))
     {
         headers.Referrer = new Uri(referrer);
     }
     headers.TryAddWithoutValidation("User-Agent", _userAgent);
 }
Exemplo n.º 23
0
 /// <summary>
 /// Copies headers from the HttpProcessor to the HttpRequestHeaders, leaving out headers defined in <see cref="dropProxyRequestHeaders"/>.
 /// </summary>
 /// <param name="p"></param>
 /// <param name="headers"></param>
 private void AddProxyableRequestHeaders(HttpProcessor p, HttpRequestHeaders headers)
 {
     foreach (KeyValuePair <string, string> header in p.httpHeadersRaw)
     {
         if (!dropProxyRequestHeaders.Contains(header.Key.ToLower()))
         {
             if (!headers.TryAddWithoutValidation(header.Key, header.Value))
             {
                 throw new Exception("Header \"" + header.Key + ": " + header.Value + "\" could not be added to HttpRequestHeaders.");
             }
         }
     }
 }
Exemplo n.º 24
0
        public void Headers_Response()
        {
            HttpRequestMessage message = new HttpRequestMessage();
            HttpRequestHeaders headers = message.Headers;

            headers.Add("Age", "vv");
            Assert.AreEqual("vv", headers.GetValues("Age").First(), "#1");

            headers.Clear();
            headers.TryAddWithoutValidation("Age", "vv");
            Assert.AreEqual("vv", headers.GetValues("Age").First(), "#2");

            Assert.AreEqual("Method: GET, RequestUri: '<null>', Version: 1.1, Content: <null>, Headers:\r\n{\r\nAge: vv\r\n}", message.ToString(), "#3");
        }
Exemplo n.º 25
0
 public override string this[string key]
 {
     get {
         try {
             return(string.Join(";", _headers.GetValues(key)));
         } catch {
             return(null);
         }
     }
     set {
         _headers.Remove(key);
         _headers.TryAddWithoutValidation(key, value);
     }
 }
Exemplo n.º 26
0
 /// <summary>
 /// 设置HttpClient的Headers值,如存在,则先移除
 /// </summary>
 public static void Set(this HttpRequestHeaders headers, string name, string value)
 {
     if (headers.Contains(name))
     {
         headers.Remove(name);
     }
     try
     {
         headers.Add(name, value);
     }
     catch (FormatException)
     {
         headers.TryAddWithoutValidation(name, value);
     }
 }
        /// <summary>
        /// Adds the specified header and its value into the <see cref="HttpHeaders"/> collection.
        /// </summary>
        /// <param name="headers">This <see cref="HttpRequestHeaders"/> instance.</param>
        /// <param name="name">The header to add to the collection.</param>
        /// <param name="value">The content of the header.</param>
        public static void AddIfNotExists(this HttpRequestHeaders headers, string name, string value)
        {
            // constants
            const StringComparison Compare = StringComparison.OrdinalIgnoreCase;

            // find
            var isExists = headers.Any(i => i.Key.Equals(name, Compare) && i.Value.Contains(value));

            // exit conditions
            if (isExists)
            {
                return;
            }
            headers.TryAddWithoutValidation(name, value);
        }
Exemplo n.º 28
0
 private static void CopyRequestHeaders(
     HttpRequestHeaders originalRequestHeaders,
     HttpRequestHeaders redirectRequestHeaders)
 {
     foreach (var header in originalRequestHeaders)
     {
         // Avoid copying the Authorization header to match the behavior
         // in the HTTP client when processing redirects
         // https://github.com/dotnet/runtime/blob/69b5d67d9418d672609aa6e2c418a3d4ae00ad18/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs#L509-L517
         if (!header.Key.Equals(HeaderNames.Authorization, StringComparison.OrdinalIgnoreCase))
         {
             redirectRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
         }
     }
 }
Exemplo n.º 29
0
        public void GetCookies_GetsCookies(string expectedCookie)
        {
            // Arrange
            HttpRequestHeaders headers = CreateHttpRequestHeaders();

            headers.TryAddWithoutValidation("Cookie", expectedCookie);

            // Act
            IEnumerable <CookieHeaderValue> cookies = headers.GetCookies();

            // Assert
            Assert.Equal(1, cookies.Count());
            string actualCookie = cookies.ElementAt(0).ToString();

            Assert.Equal(expectedCookie, actualCookie);
        }
Exemplo n.º 30
0
        private static void UpdateHeaders(HttpRequestHeaders requestHeaders, IEnumerable <KeyValuePair <string, string> > headers)
        {
            if (requestHeaders == null)
            {
                throw new ArgumentNullException(nameof(requestHeaders));
            }
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            foreach (KeyValuePair <string, string> item in headers)
            {
                requestHeaders.TryAddWithoutValidation(item.Key, item.Value);
            }
        }