Exemplo n.º 1
0
        public HttpRequest()
        {
            Protocol = DEFAULT_HTTP_PROTOCOL;

            GET = new HttpRequestParams();
            POST = new HttpRequestParams();
            FILES = new HttpFormFiles();
            Headers = new HttpRequestHeaders();
            Cookies = new HttpCookies();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Send an HTTP request to the specified 'url'.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="headers"></param>
        /// <param name="content"></param>
        /// <param name="onError"></param>
        /// <exception cref="HttpClientRequestException">Response did not return a success status code.</exception>
        /// <returns></returns>
        public virtual async Task <TModel> SendAsync <TModel>(string url, HttpMethod method, HttpRequestHeaders headers, HttpContent content = null, Func <HttpResponseMessage, bool> onError = null)
        {
            var response = await SendAsync(url, method, headers, content);

            if (response.IsSuccessStatusCode)
            {
                return(await DeserializeAsync <TModel>(response));
            }

            // If the error handle is not provided, or if it returns false throw an error.
            if (!(onError?.Invoke(response) ?? false))
            {
                var error = new HttpClientRequestException(response);
                _logger.LogError(error, error.Message);
                throw error;
            }

            return(default);
Exemplo n.º 3
0
 /// <summary>
 /// Send an HTTP request to the specified 'uri'.
 /// </summary>
 /// <param name="uri"></param>
 /// <param name="method"></param>
 /// <param name="headers"></param>
 /// <param name="content"></param>
 /// <returns></returns>
 public virtual async Task <HttpResponseMessage> SendAsync(Uri url, HttpMethod method, HttpRequestHeaders headers, HttpContent content = null)
 {
     return(await SendAsync(url.OriginalString, method, headers, content));
 }
Exemplo n.º 4
0
        /// <summary>
        /// Send an HTTP request to the specified 'url'.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="headers"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public virtual Task <HttpResponseMessage> SendAsync(string url, HttpMethod method, HttpRequestHeaders headers, HttpContent content = null)
        {
            if (String.IsNullOrWhiteSpace(url))
            {
                throw new ArgumentException($"Argument '{nameof(url)}' must be a valid URL.");
            }

            return(this.SendInternalAsync(url, method, headers, content));
        }
Exemplo n.º 5
0
        public void Headers_Invalid()
        {
            HttpRequestMessage message = new HttpRequestMessage();
            HttpRequestHeaders headers = message.Headers;

            try {
                headers.Add("Allow", "");
                Assert.Fail("#1");
            } catch (InvalidOperationException) {
            }

            try {
                headers.Add(null, "");
                Assert.Fail("#2");
            } catch (ArgumentException) {
            }

            try {
                headers.Add("mm", null as IEnumerable <string>);
                Assert.Fail("#2b");
            } catch (ArgumentNullException) {
            }

            try {
                headers.Add("accept", "audio");
                Assert.Fail("#2c");
            } catch (FormatException) {
            }

            Assert.IsFalse(headers.TryAddWithoutValidation("Allow", ""), "#3");;

            Assert.IsFalse(headers.TryAddWithoutValidation(null, ""), "#4");

            try {
                headers.Contains(null);
                Assert.Fail("#5");
            } catch (ArgumentException) {
            }

            try {
                headers.GetValues(null);
                Assert.Fail("#6a");
            } catch (ArgumentException) {
            }

            try {
                headers.GetValues("bbbb");
                Assert.Fail("#6b");
            } catch (InvalidOperationException) {
            }

            try {
                headers.Add("from", new[] { "*****@*****.**", "*****@*****.**" });
                Assert.Fail("#7a");
            } catch (FormatException) {
            }

            Assert.IsTrue(headers.TryAddWithoutValidation("from", "*****@*****.**"), "#7-0");
            try {
                headers.Add("from", "*****@*****.**");
                Assert.Fail("#7b");
            } catch (FormatException) {
            }
        }
Exemplo n.º 6
0
        public void Headers()
        {
            HttpRequestMessage message = new HttpRequestMessage();
            HttpRequestHeaders headers = message.Headers;

            headers.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/x"));
            headers.AcceptCharset.Add(new StringWithQualityHeaderValue("str-v", 0.002));
            headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("str-enc", 0.44));
            headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("str-lang", 0.41));
            headers.Authorization = new AuthenticationHeaderValue("sh-aut", "par");
            headers.CacheControl  = new CacheControlHeaderValue()
            {
                MaxAge = TimeSpan.MaxValue
            };
            headers.Connection.Add("test-value");
            headers.ConnectionClose = true;
            headers.Date            = new DateTimeOffset(DateTime.Today);
            headers.Expect.Add(new NameValueWithParametersHeaderValue("en", "ev"));
            headers.ExpectContinue = true;
            headers.From           = "*****@*****.**";
            headers.Host           = "host";
            headers.IfMatch.Add(new EntityTagHeaderValue("\"tag\"", true));
            headers.IfModifiedSince = new DateTimeOffset(DateTime.Today);
            headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"tag2\"", true));
            headers.IfRange           = new RangeConditionHeaderValue(new DateTimeOffset(DateTime.Today));
            headers.IfUnmodifiedSince = new DateTimeOffset? (DateTimeOffset.Now);
            headers.MaxForwards       = 0x15b3;
            headers.Pragma.Add(new NameValueHeaderValue("name", "value"));
            headers.ProxyAuthorization = new AuthenticationHeaderValue("s", "p");
            headers.Range    = new RangeHeaderValue(5L, 30L);
            headers.Referrer = new Uri("http://xamarin.com");
            headers.TE.Add(new TransferCodingWithQualityHeaderValue("TE", 0.3));
            headers.Trailer.Add("value");
            headers.TransferEncoding.Add(new TransferCodingHeaderValue("tchv"));
            headers.TransferEncodingChunked = true;
            headers.Upgrade.Add(new ProductHeaderValue("prod", "ver"));
            headers.UserAgent.Add(new ProductInfoHeaderValue("(comment)"));
            headers.Via.Add(new ViaHeaderValue("protocol", "rec-by"));
            headers.Warning.Add(new WarningHeaderValue(5, "agent", "\"txt\""));

            try {
                headers.Add("authorization", "");
                Assert.Fail("Authorization");
            } catch (FormatException) {
            }

            try {
                headers.Add("connection", "extra ß ");
                Assert.Fail("Date");
            } catch (FormatException) {
            }

            try {
                headers.Add("date", "");
                Assert.Fail("Date");
            } catch (FormatException) {
            }

            try {
                headers.Add("from", "*****@*****.**");
                Assert.Fail("From");
            } catch (FormatException) {
            }

            try {
                headers.Add("hOst", "host");
                Assert.Fail("Host");
            } catch (FormatException) {
            }

            try {
                headers.Add("if-modified-since", "");
                Assert.Fail("if-modified-since");
            } catch (FormatException) {
            }

            try {
                headers.Add("if-range", "");
                Assert.Fail("if-range");
            } catch (FormatException) {
            }

            try {
                headers.Add("if-unmodified-since", "");
                Assert.Fail("if-unmodified-since");
            } catch (FormatException) {
            }

            try {
                headers.Add("max-forwards", "");
                Assert.Fail("max-forwards");
            } catch (FormatException) {
            }

            try {
                headers.Add("proxy-authorization", "");
                Assert.Fail("proxy-authorization");
            } catch (FormatException) {
            }

            try {
                headers.Add("range", "");
            } catch (FormatException) {
            }

            try {
                headers.Add("referer", "");
                Assert.Fail("referer");
            } catch (FormatException) {
            }

            try {
                headers.Add("pragma", "nocache,RequestID=1,g=");
                Assert.Fail("pragma");
            } catch (FormatException) {
            }

            headers.Add("accept", "audio/y");
            headers.Add("accept-charset", "achs");
            headers.Add("accept-encoding", "aenc");
            headers.Add("accept-language", "alan");
            headers.Add("expect", "exp");
            headers.Add("if-match", "\"v\"");
            headers.Add("if-none-match", "\"v2\"");
            headers.Add("TE", "0.8");
            headers.Add("trailer", "value2");
            headers.Add("transfer-encoding", "ttt");
            headers.Add("upgrade", "uuu");
            headers.Add("user-agent", "uaua");
            headers.Add("via", "prot v");
            headers.Add("warning", "4 ww \"t\"");
            headers.Add("pragma", "nocache,R=1,g");

            Assert.IsTrue(headers.Accept.SequenceEqual(
                              new[] {
                new MediaTypeWithQualityHeaderValue("audio/x"),
                new MediaTypeWithQualityHeaderValue("audio/y")
            }
                              ));

            Assert.IsTrue(headers.AcceptCharset.SequenceEqual(
                              new[] {
                new StringWithQualityHeaderValue("str-v", 0.002),
                new StringWithQualityHeaderValue("achs")
            }
                              ));

            Assert.IsTrue(headers.AcceptEncoding.SequenceEqual(
                              new[] {
                new StringWithQualityHeaderValue("str-enc", 0.44),
                new StringWithQualityHeaderValue("aenc")
            }
                              ));

            Assert.IsTrue(headers.AcceptLanguage.SequenceEqual(
                              new[] {
                new StringWithQualityHeaderValue("str-lang", 0.41),
                new StringWithQualityHeaderValue("alan")
            }
                              ));

            Assert.AreEqual(new AuthenticationHeaderValue("sh-aut", "par"), headers.Authorization);

            var cch = new CacheControlHeaderValue()
            {
                MaxAge = TimeSpan.MaxValue,
            };

            Assert.AreEqual(cch, headers.CacheControl);

            Assert.IsTrue(headers.Connection.SequenceEqual(
                              new string[] { "test-value", "close" }));

            Assert.AreEqual(headers.Date, new DateTimeOffset(DateTime.Today));

            Assert.IsTrue(headers.Expect.SequenceEqual(
                              new [] {
                new NameValueWithParametersHeaderValue("en", "ev"),
                new NameValueWithParametersHeaderValue("100-continue"),
                new NameValueWithParametersHeaderValue("exp")
            }));

            Assert.AreEqual(headers.From, "*****@*****.**");

            Assert.IsTrue(headers.IfMatch.SequenceEqual(
                              new EntityTagHeaderValue[] {
                new EntityTagHeaderValue("\"tag\"", true),
                new EntityTagHeaderValue("\"v\"", false)
            }
                              ));

            Assert.AreEqual(headers.IfModifiedSince, new DateTimeOffset(DateTime.Today));
            Assert.IsTrue(headers.IfNoneMatch.SequenceEqual(new EntityTagHeaderValue[] { new EntityTagHeaderValue("\"tag2\"", true), new EntityTagHeaderValue("\"v2\"", false) }));
            Assert.AreEqual(new DateTimeOffset(DateTime.Today), headers.IfRange.Date);
            Assert.AreEqual(headers.MaxForwards, 0x15b3);
            Assert.AreEqual("p", headers.ProxyAuthorization.Parameter);
            Assert.AreEqual("s", headers.ProxyAuthorization.Scheme);
            Assert.AreEqual(5, headers.Range.Ranges.First().From);
            Assert.AreEqual(30, headers.Range.Ranges.First().To);
            Assert.AreEqual("bytes", headers.Range.Unit);
            Assert.AreEqual(headers.Referrer, new Uri("http://xamarin.com"));
            Assert.IsTrue(headers.TE.SequenceEqual(new TransferCodingWithQualityHeaderValue[] { new TransferCodingWithQualityHeaderValue("TE", 0.3), new TransferCodingWithQualityHeaderValue("0.8") }), "29");
            Assert.IsTrue(headers.Trailer.SequenceEqual(
                              new string[] {
                "value", "value2"
            }), "30");

            Assert.IsTrue(headers.TransferEncoding.SequenceEqual(
                              new[] {
                new TransferCodingHeaderValue("tchv"),
                new TransferCodingHeaderValue("chunked"),
                new TransferCodingHeaderValue("ttt")
            }
                              ));

            Assert.IsTrue(headers.Upgrade.SequenceEqual(
                              new[] {
                new ProductHeaderValue("prod", "ver"),
                new ProductHeaderValue("uuu")
            }
                              ));

            Assert.IsTrue(headers.UserAgent.SequenceEqual(
                              new[] {
                new ProductInfoHeaderValue("(comment)"),
                new ProductInfoHeaderValue("uaua", null)
            }
                              ));

            Assert.IsTrue(headers.Via.SequenceEqual(
                              new[] {
                new ViaHeaderValue("protocol", "rec-by"),
                new ViaHeaderValue("prot", "v")
            }
                              ));

            Assert.IsTrue(headers.Warning.SequenceEqual(
                              new[] {
                new WarningHeaderValue(5, "agent", "\"txt\""),
                new WarningHeaderValue(4, "ww", "\"t\"")
            }
                              ));

            Assert.IsTrue(headers.Pragma.SequenceEqual(
                              new[] {
                new NameValueHeaderValue("name", "value"),
                new NameValueHeaderValue("nocache", null),
                new NameValueHeaderValue("R", "1"),
                new NameValueHeaderValue("g", null)
            }
                              ));
        }
Exemplo n.º 7
0
 public static string ValueFor(this IEnumerable <Header> headers, HttpRequestHeader header)
 {
     return(headers.ValueFor(HttpRequestHeaders.HeaderNameFor(header)));
 }
Exemplo n.º 8
0
 private void PostProcessRequestHttpHeadersCallback(HttpRequestMessage Request, HttpRequestHeaders DefaultRequestHeaders)
 {
     this.DebugMsg("PreProcessHeadRequestHeadersCallback Called");
 }
Exemplo n.º 9
0
 public static void SetBearerAuthentication(this HttpRequestHeaders headers, string token)
 {
     headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
 }
Exemplo n.º 10
0
        public static void SetBasicAuthentication(this HttpRequestHeaders headers, string username, string password)
        {
            var bytes = Encoding.UTF8.GetBytes($"{username}:{password}");

            headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));
        }
Exemplo n.º 11
0
        private static void AddRequestHeaders(HttpWebRequest request, HttpRequestHeaders headers)
        {
            foreach (var header in headers)
            {
                switch (header.Key.ToLowerInvariant())
                {
                case "accept":
                    request.Accept = headers.Accept.ToString();
                    break;

                case "connection":
                    request.Connection = headers.Connection.ToString();
                    break;

                case "date":
                    // .NET 3.5 does not expose a property for setting this reserved header
                    goto default;

                case "expect":
                    request.Expect = headers.Expect.ToString();
                    break;

                case "host":
                    // .NET 3.5 does not expose a property for setting this reserved header
                    goto default;

                case "if-modified-since":
                    request.IfModifiedSince = headers.IfModifiedSince.Value.UtcDateTime;
                    break;

                case "range":
                    foreach (var range in headers.Range.Ranges)
                    {
                        checked
                        {
                            if (!string.IsNullOrEmpty(headers.Range.Unit))
                            {
                                if (range.To.HasValue)
                                {
                                    request.AddRange(headers.Range.Unit, (int)range.From.Value, (int)range.To.Value);
                                }
                                else
                                {
                                    request.AddRange(headers.Range.Unit, (int)range.From.Value);
                                }
                            }
                            else
                            {
                                if (range.To.HasValue)
                                {
                                    request.AddRange((int)range.From.Value, (int)range.To.Value);
                                }
                                else
                                {
                                    request.AddRange((int)range.From.Value);
                                }
                            }
                        }
                    }

                    break;

                case "referer":
                    request.Referer = headers.Referrer.OriginalString;
                    break;

                case "transfer-encoding":
                    request.TransferEncoding = headers.TransferEncoding.ToString();
                    break;

                case "user-agent":
                    request.UserAgent = headers.UserAgent.ToString();
                    break;

                default:
                    foreach (var value in header.Value)
                    {
                        request.Headers.Add(header.Key, value);
                    }

                    break;
                }
            }
        }
Exemplo n.º 12
0
        UpdateCardholderAsync(object query, PropertyBag body, string newSafeKey = null, string safeKey = null, Paging paging = null, HttpRequestHeaders headers = null)
        {
            QueryDef qd   = new QueryDef(query, body);
            string   path = "/cardholders";

            if (headers == null)
            {
                headers = new HttpRequestMessage().Headers;
            }
            AddNewSafeKeyHeader(headers, newSafeKey);
            return(await ApiMultiPutDelAsync <Cardholder>(path, null, qd, HttpMethod.Put, body, null, paging, headers));
        }
Exemplo n.º 13
0
        CreateCardholderAsync(PropertyBag body, string safeKey = null, string financialInstitution = null, HttpRequestHeaders headers = null)
        {
            if (headers == null)
            {
                headers = new HttpRequestMessage().Headers;
            }
            AddSafeKeyHeader(headers, safeKey);
            if (financialInstitution != null)
            {
                headers.Add("x-cardsavr-financial-institution", financialInstitution);
            }

            return(await ApiPostAsync <Cardholder>("/cardholders", body, null, headers));
        }
 internal void AddHeaders(HttpRequestHeaders headers)
 {
     foreach (var header in headers) {
         TryAddWithoutValidation (header.Key, header.Value);
     }
 }
        /// <returns>
        /// The first value is the canonical request, the second value is the signed headers.
        /// </returns>
        public static async Task <(string, string)> BuildAsync(
            HttpRequestMessage request,
            HttpRequestHeaders defaultHeaders)
        {
            var builder = new StringBuilder();

            // The HTTP request method (GET, PUT, POST, etc.), followed by a newline character
            builder.Append($"{request.Method}\n");

            // Add the canonical URI parameter, followed by a newline character. The canonical URI
            // is the URI-encoded version of the absolute path component of the URI, which is
            // everything in the URI from the HTTP host to the question mark character ("?") that
            // begins the query string parameters (if any).
            //
            // Normalize URI paths according to <see href="https://tools.ietf.org/html/rfc3986">RFC
            // 3986</see>. Remove redundant and relative path components. Each path segment must be
            // URI-encoded twice (
            // <see href="https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html">
            // except for Amazon S3 which only gets URI-encoded once</see>).
            var pathSegments = request.RequestUri.AbsolutePath
                               .Replace("//", "/")
                               .Split('/')
                               .Select(pathSegment => AWSSDKUtils.UrlEncode(pathSegment, false));

            builder.Append($"{string.Join("/", pathSegments)}\n");

            // Add the canonical query string, followed by a newline character. If the request does
            // not include a query string, use an empty string (essentially, a blank line).
            //
            // To construct the canonical query string, complete the following steps:
            //
            // a. Sort the parameter names by character code point in ascending order. Parameters
            //    with duplicate names should be sorted by value. For example, a parameter name
            //    that begins with the uppercase letter F precedes a parameter name that begins
            //    with a lowercase letter b.
            // b. URI-encode each parameter name and value according to the following rules:
            //    - Do not URI-encode any of the unreserved characters that RFC 3986 defines: A-Z,
            //      a-z, 0-9, hyphen ( - ), underscore ( _ ), period ( . ), and tilde ( ~ ).
            //    - Percent-encode all other characters with %XY, where X and Y are hexadecimal
            //      characters (0-9 and uppercase A-F). For example, the space character must be
            //      encoded as %20 (not using '+', as some encoding schemes do) and extended UTF-8
            //      characters must be in the form %XY%ZA%BC.
            // c. Build the canonical query string by starting with the first parameter name in the
            //    sorted list.
            // d. For each parameter, append the URI-encoded parameter name, followed by the equals
            //    sign character (=), followed by the URI-encoded parameter value. Use an empty
            //    string for parameters that have no value.
            // e. Append the ampersand character (&) after each parameter value, except for the
            //    last value in the list.
            var parameters = SortQueryParameters(request.RequestUri.Query)
                             .SelectMany(
                parameter => parameter.Value.Select(
                    parameterValue => $"{AWSSDKUtils.UrlEncode(parameter.Key, false)}={AWSSDKUtils.UrlEncode(parameterValue, false)}"));

            builder.Append($"{string.Join("&", parameters)}\n");

            // Add the canonical headers, followed by a newline character. The canonical headers
            // consist of a list of all the HTTP headers that you are including with the signed
            // request.
            //
            // To create the canonical headers list, convert all header names to lowercase and
            // remove leading spaces and trailing spaces. Convert sequential spaces in the header
            // value to a single space.
            //
            // Build the canonical headers list by sorting the (lowercase) headers by character
            // code and then iterating through the header names. Construct each header according to
            // the following rules:
            //
            // - Append the lowercase header name followed by a colon.
            // - Append a comma-separated list of values for that header. Do not sort the values in
            //   headers that have multiple values.
            //   PLEASE NOTE: Microsoft has chosen to separate the header values with ", ", not ","
            //   as defined by the Canonical Request algorithm.
            // - Append a new line ('\n').
            var sortedHeaders = SortHeaders(request.Headers, defaultHeaders);

            foreach (var header in sortedHeaders)
            {
                builder.Append($"{header.Key}:{string.Join(HeaderValueSeparator, header.Value)}\n");
            }

            builder.Append('\n');

            // Add the signed headers, followed by a newline character. This value is the list of
            // headers that you included in the canonical headers. By adding this list of headers,
            // you tell AWS which headers in the request are part of the signing process and which
            // ones AWS can ignore (for example, any additional headers added by a proxy) for
            // purposes of validating the request.
            //
            // To create the signed headers list, convert all header names to lowercase, sort them
            // by character code, and use a semicolon to separate the header names.
            //
            // Build the signed headers list by iterating through the collection of header names,
            // sorted by lowercase character code. For each header name except the last, append a
            // semicolon (';') to the header name to separate it from the following header name.
            var signedHeaders = string.Join(";", sortedHeaders.Keys);

            builder.Append($"{signedHeaders}\n");

            // Use a hash (digest) function like SHA256 to create a hashed value from the payload
            // in the body of the HTTP or HTTPS request.
            //
            // If the payload is empty, use an empty string as the input to the hash function.
            var requestPayload = request.Content != null
                ? await request.Content.ReadAsByteArrayAsync()
                : new byte[0];

            var hash = AWS4Signer.ComputeHash(requestPayload);
            var hex  = AWSSDKUtils.ToHex(hash, true);

            builder.Append(hex);

            return(builder.ToString(), signedHeaders);
        }
Exemplo n.º 16
0
 /// <summary>
 /// A default constructor that initialises all fields to their defaults.
 /// </summary>
 internal HttpRequest()
 {
     Headers = new HttpRequestHeaders();
 }
Exemplo n.º 17
0
 public HttpRequestHeaders AddSubscriptionHeader(HttpRequestHeaders headers)
 {
     headers.Add(_azureSettings.OcpApimSubscriptionKeyHeader, _azureSettings.ApiKey);
     return(headers);
 }
Exemplo n.º 18
0
        public async Task CopyToAsyncDoesNotCopyBlocks()
        {
            var writeCount      = 0;
            var writeTcs        = new TaskCompletionSource <(byte[], int, int)>(TaskCreationOptions.RunContinuationsAsynchronously);
            var mockDestination = new Mock <Stream>()
            {
                CallBase = true
            };

            mockDestination
            .Setup(m => m.WriteAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <int>(), CancellationToken.None))
            .Callback((byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
            {
                writeTcs.SetResult((buffer, offset, count));
                writeCount++;
            })
            .Returns(Task.CompletedTask);

            using (var memoryPool = KestrelMemoryPool.Create())
            {
                var options                = new PipeOptions(pool: memoryPool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false);
                var pair                   = DuplexPipe.CreateConnectionPair(options, options);
                var transport              = pair.Transport;
                var application            = pair.Application;
                var http1ConnectionContext = new Http1ConnectionContext
                {
                    ServiceContext     = new TestServiceContext(),
                    ConnectionFeatures = new FeatureCollection(),
                    Application        = application,
                    Transport          = transport,
                    MemoryPool         = memoryPool,
                    TimeoutControl     = Mock.Of <ITimeoutControl>()
                };
                var http1Connection = new Http1Connection(http1ConnectionContext)
                {
                    HasStartedConsumingRequestBody = true
                };

                var headers = new HttpRequestHeaders {
                    HeaderContentLength = "12"
                };
                var body = Http1MessageBody.For(HttpVersion.Http11, headers, http1Connection);

                var copyToAsyncTask = body.CopyToAsync(mockDestination.Object);

                var bytes  = Encoding.ASCII.GetBytes("Hello ");
                var buffer = http1Connection.RequestBodyPipe.Writer.GetMemory(2048);
                ArraySegment <byte> segment;
                Assert.True(MemoryMarshal.TryGetArray(buffer, out segment));
                Buffer.BlockCopy(bytes, 0, segment.Array, segment.Offset, bytes.Length);
                http1Connection.RequestBodyPipe.Writer.Advance(bytes.Length);
                await http1Connection.RequestBodyPipe.Writer.FlushAsync();

                // Verify the block passed to Stream.WriteAsync() is the same one incoming data was written into.
                Assert.Equal((segment.Array, segment.Offset, bytes.Length), await writeTcs.Task);

                // Verify the again when GetMemory returns the tail space of the same block.
                writeTcs = new TaskCompletionSource <(byte[], int, int)>(TaskCreationOptions.RunContinuationsAsynchronously);
                bytes    = Encoding.ASCII.GetBytes("World!");
                buffer   = http1Connection.RequestBodyPipe.Writer.GetMemory(2048);
                Assert.True(MemoryMarshal.TryGetArray(buffer, out segment));
                Buffer.BlockCopy(bytes, 0, segment.Array, segment.Offset, bytes.Length);
                http1Connection.RequestBodyPipe.Writer.Advance(bytes.Length);
                await http1Connection.RequestBodyPipe.Writer.FlushAsync();

                Assert.Equal((segment.Array, segment.Offset, bytes.Length), await writeTcs.Task);

                http1Connection.RequestBodyPipe.Writer.Complete();

                await copyToAsyncTask;

                Assert.Equal(2, writeCount);

                // Don't call body.StopAsync() because PumpAsync() was never called.
                http1Connection.RequestBodyPipe.Reader.Complete();
            }
        }
 private static Dictionary <string, StringValues> CopyWithoutContentHeaders(HttpRequestHeaders sourceHeaders)
 {
     return(sourceHeaders.Where(h => !h.Key.ToLowerInvariant().StartsWith("content-"))
            .ToDictionary(v => v.Key, v => new StringValues(v.Value.ToArray())));
 }
Exemplo n.º 20
0
        private static void SetRequestHeaders(HttpWebRequest webRequest, HttpRequestMessage request)
        {
            WebHeaderCollection webRequestHeaders = webRequest.Headers;
            HttpRequestHeaders  headers           = request.Headers;

            // Most headers are just added directly to HWR's internal headers collection. But there are some exceptions
            // requiring different handling.
            // The following bool vars are used to skip string comparison when not required: E.g. if the 'Host' header
            // was not set, we don't need to compare every header in the collection with 'Host' to make sure we don't
            // add it to HWR's header collection.
            bool isHostSet             = headers.Contains(HttpKnownHeaderNames.Host);
            bool isExpectSet           = headers.Contains(HttpKnownHeaderNames.Expect);
            bool isTransferEncodingSet = headers.Contains(HttpKnownHeaderNames.TransferEncoding);
            bool isConnectionSet       = headers.Contains(HttpKnownHeaderNames.Connection);

            if (isHostSet)
            {
                string host = headers.Host;
                if (host != null)
                {
                    webRequest.Host = host;
                }
            }

            // The following headers (Expect, Transfer-Encoding, Connection) have both a collection property and a
            // bool property indicating a special value. Internally (in HttpHeaders) we don't distinguish between
            // "special" values and other values. So we must make sure that we add all but the special value to HWR.
            // E.g. the 'Transfer-Encoding: chunked' value must be set using HWR.SendChunked, whereas all other values
            // can be added to the 'Transfer-Encoding'.
            if (isExpectSet)
            {
                string expectHeader = headers.Expect.GetHeaderStringWithoutSpecial();
                // Was at least one non-special value set?
                if (!String.IsNullOrEmpty(expectHeader) || !headers.Expect.IsSpecialValueSet)
                {
                    webRequestHeaders.AddInternal(HttpKnownHeaderNames.Expect, expectHeader);
                }
            }

            if (isTransferEncodingSet)
            {
                string transferEncodingHeader = headers.TransferEncoding.GetHeaderStringWithoutSpecial();
                // Was at least one non-special value set?
                if (!String.IsNullOrEmpty(transferEncodingHeader) || !headers.TransferEncoding.IsSpecialValueSet)
                {
                    webRequestHeaders.AddInternal(HttpKnownHeaderNames.TransferEncoding, transferEncodingHeader);
                }
            }

            if (isConnectionSet)
            {
                string connectionHeader = headers.Connection.GetHeaderStringWithoutSpecial();

                // Was at least one non-special value set?
                if (!String.IsNullOrEmpty(connectionHeader) || !headers.Connection.IsSpecialValueSet)
                {
                    webRequestHeaders.AddInternal(HttpKnownHeaderNames.Connection, connectionHeader);
                }
            }

            foreach (var header in request.Headers.GetHeaderStrings())
            {
                string headerName = header.Key;

                if ((isHostSet && AreEqual(HttpKnownHeaderNames.Host, headerName)) ||
                    (isExpectSet && AreEqual(HttpKnownHeaderNames.Expect, headerName)) ||
                    (isTransferEncodingSet && AreEqual(HttpKnownHeaderNames.TransferEncoding, headerName)) ||
                    (isConnectionSet && AreEqual(HttpKnownHeaderNames.Connection, headerName)))
                {
                    continue; // Header was already added.
                }

                // Use AddInternal() to skip validation.
                webRequestHeaders.AddInternal(header.Key, header.Value);
            }
        }
 public HeaderValueProvider(HttpRequestHeaders headers)
 {
     _headers = headers;
 }
Exemplo n.º 22
0
        public void Header_BaseImplementation()
        {
            HttpRequestMessage message = new HttpRequestMessage();
            HttpRequestHeaders headers = message.Headers;

            headers.Add("a", "a-value");
            headers.Add("b", new List <string> {
                "v1", "v2"
            });
            headers.Add("c", null as string);
            headers.Add("d", new string[0]);

            Assert.IsTrue(headers.TryAddWithoutValidation("accept", "audio"), "#0");

            Assert.IsFalse(headers.Contains("nn"), "#1a");
            Assert.IsTrue(headers.Contains("b"), "#1b");

            var values = headers.GetValues("b").ToList();

            Assert.AreEqual("v1", values[0], "#2a");
            Assert.AreEqual("v2", values[1], "#2b");

            Assert.IsFalse(headers.Remove("p"), "#3a");
            Assert.IsTrue(headers.Remove("b"), "#3b");
            Assert.IsFalse(headers.Contains("b"), "#3b-c");

            IEnumerable <string> values2;

            Assert.IsTrue(headers.TryGetValues("c", out values2));
            values = values2.ToList();
            Assert.AreEqual("", values[0], "#4a");

            int counter = 0;

            foreach (var i in headers)
            {
                ++counter;
            }

            Assert.AreEqual(3, counter, "#5");

            headers.Clear();

            headers.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/x"));
            Assert.IsTrue(headers.TryAddWithoutValidation("accept", "audio"), "#55");

            values = headers.GetValues("accept").ToList();
            Assert.AreEqual(2, values.Count, "#6");
            Assert.AreEqual("audio/x", values[0], "#6a");
            Assert.AreEqual("audio", values[1], "#6b");
            Assert.AreEqual(1, headers.Accept.Count, "#6c");

            headers.Clear();

            Assert.IsTrue(headers.TryAddWithoutValidation("from", new[] { "*****@*****.**", "*****@*****.**" }), "#70");
            values = headers.GetValues("from").ToList();

            Assert.AreEqual(2, values.Count, "#7");
            Assert.AreEqual("*****@*****.**", values[0], "#7a");
            Assert.AreEqual("*****@*****.**", values[1], "#7b");
            Assert.AreEqual("*****@*****.**", headers.From, "#7c");

            headers.Clear();

            Assert.IsTrue(headers.TryAddWithoutValidation("Date", "wrong date"), "#8-0");
            var value = headers.Date;

            Assert.IsNull(headers.Date, "#8");
        }
Exemplo n.º 23
0
        public void Headers_MultiValues()
        {
            HttpRequestMessage message = new HttpRequestMessage();
            HttpRequestHeaders headers = message.Headers;

            headers.Add("Accept", "application/vnd.citrix.requesttokenresponse+xml, application/vnd.citrix.requesttokenchoices+xml");
            headers.Add("Accept-Charset", "aa ;Q=0,bb;Q=1");
            headers.Add("Expect", "x=1; v, y=5");
            headers.Add("If-Match", "\"a\",*, \"b\",*");
            headers.Add("user-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36");

            Assert.AreEqual(2, headers.Accept.Count, "#1a");
            Assert.IsTrue(headers.Accept.SequenceEqual(
                              new[] {
                new MediaTypeWithQualityHeaderValue("application/vnd.citrix.requesttokenresponse+xml"),
                new MediaTypeWithQualityHeaderValue("application/vnd.citrix.requesttokenchoices+xml"),
            }
                              ), "#1b");

            Assert.AreEqual(2, headers.AcceptCharset.Count, "#2a");
            Assert.IsTrue(headers.AcceptCharset.SequenceEqual(
                              new[] {
                new StringWithQualityHeaderValue("aa", 0),
                new StringWithQualityHeaderValue("bb", 1),
            }
                              ), "#2b");

            Assert.AreEqual(2, headers.Expect.Count, "#3a");
            var expect_expected = new[] {
                new NameValueWithParametersHeaderValue("x", "1")
                {
                },
                new NameValueWithParametersHeaderValue("y", "5"),
            };

            expect_expected [0].Parameters.Add(new NameValueHeaderValue("v"));
            Assert.IsTrue(headers.Expect.SequenceEqual(
                              expect_expected
                              ), "#3b");

            Assert.AreEqual(4, headers.IfMatch.Count, "#4a");
            Assert.IsTrue(headers.IfMatch.SequenceEqual(
                              new[] {
                new EntityTagHeaderValue("\"a\""),
                EntityTagHeaderValue.Any,
                new EntityTagHeaderValue("\"b\""),
                EntityTagHeaderValue.Any
            }
                              ), "#4b");

            Assert.AreEqual(6, headers.UserAgent.Count, "#10a");

            Assert.IsTrue(headers.UserAgent.SequenceEqual(
                              new[] {
                new ProductInfoHeaderValue("Mozilla", "5.0"),
                new ProductInfoHeaderValue("(Macintosh; Intel Mac OS X 10_8_4)"),
                new ProductInfoHeaderValue("AppleWebKit", "537.36"),
                new ProductInfoHeaderValue("(KHTML, like Gecko)"),
                new ProductInfoHeaderValue("Chrome", "29.0.1547.62"),
                new ProductInfoHeaderValue("Safari", "537.36")
            }
                              ), "#10b");
        }
Exemplo n.º 24
0
 private static void GoogleTraceContextEmitter(HttpRequestHeaders headers, string traceId, ulong?spanId, bool?shouldTrace) =>
 // To mimic incoming requests with the Google trace header.
 headers.Add(TraceHeaderContext.TraceHeader, TraceHeaderContext.Create(traceId, spanId, shouldTrace).ToString());
Exemplo n.º 25
0
 public void GetServiceHeader(HttpRequestHeaders headers)
 {
 }
Exemplo n.º 26
0
 /// <summary>
 /// Send an HTTP request to the specified 'uri'.
 /// </summary>
 /// <param name="uri"></param>
 /// <param name="method"></param>
 /// <param name="headers"></param>
 /// <param name="data"></param>
 /// <returns></returns>
 public virtual async Task <HttpResponseMessage> SendJsonAsync <T>(Uri url, HttpMethod method, HttpRequestHeaders headers, T data = null)
     where T : class
 {
     return(await SendJsonAsync(url.OriginalString, method, headers, data));
 }
Exemplo n.º 27
0
 private void AddDefaultRequestHeaders(HttpRequestHeaders headers)
 {
     headers.Add("Accept", "application/json");
 }
Exemplo n.º 28
0
 /// <summary>
 /// Send an HTTP request to the specified 'url'.
 /// </summary>
 /// <param name="url"></param>
 /// <param name="method"></param>
 /// <param name="headers"></param>
 /// <param name="data"></param>
 /// <param name="onError"></param>
 /// <exception cref="HttpClientRequestException">Response did not return a success status code.</exception>
 /// <returns></returns>
 public virtual async Task <TModel> SendJsonAsync <TModel, T>(string url, HttpMethod method, HttpRequestHeaders headers, T data = null, Func <HttpResponseMessage, bool> onError = null)
     where T : class
 {
     if (data != null)
     {
         var json = JsonSerializer.Serialize(data, _serializeOptions);
         using var content = new StringContent(json, Encoding.UTF8, "application/json");
         return(await SendAsync <TModel>(url, method, headers, content, onError));
     }
     else
     {
         return(await SendAsync <TModel>(url, method, headers, null, onError));
     }
 }
Exemplo n.º 29
0
        /** -------------------------------------------------------------------- **/

        private void PostProcessRequestHttpHeadersCallback(HttpRequestMessage Request, HttpRequestHeaders DefaultRequestHeaders)
        {
        }
        public static SortedDictionary <string, List <string> > SortHeaders(
            HttpRequestHeaders headers,
            HttpRequestHeaders defaultHeaders)
        {
            var sortedHeaders = new SortedDictionary <string, List <string> >(StringComparer.Ordinal);

            string FormatHeaderName(string headerName)
            {
                return(headerName.ToLowerInvariant());
            }

            void AddHeader(KeyValuePair <string, IEnumerable <string> > header)
            {
                var headerName = FormatHeaderName(header.Key);

                // Create header if it doesn't already exist
                if (!sortedHeaders.TryGetValue(headerName, out var headerValues))
                {
                    headerValues = new List <string>();
                    sortedHeaders.Add(headerName, headerValues);
                }

                // Remove leading and trailing header value spaces, and convert sequential spaces
                // into a single space
                headerValues.AddRange(header.Value.Select(headerValue => headerValue.Trim().NormalizeWhiteSpace()));
            }

            void AddDefaultDotnetHeaders()
            {
                foreach (var defaultHeader in defaultHeaders)
                {
                    // On .NET Framework or .NET Core we only add header values if they're not
                    // already added on the message. Note that we don't merge collections: If both
                    // the default headers and the message have set some values for a certain
                    // header, then we don't try to merge the values.
                    if (!sortedHeaders.ContainsKey(FormatHeaderName(defaultHeader.Key)))
                    {
                        AddHeader(defaultHeader);
                    }
                }
            }

            void AddDefaultMonoHeaders()
            {
                foreach (var defaultHeader in defaultHeaders)
                {
                    // On Mono we add header values indifferent of whether the header already exists
                    AddHeader(defaultHeader);
                }
            }

            // Add headers
            foreach (var header in headers)
            {
                AddHeader(header);
            }

            // Add default headers
            if (defaultHeaders != null)
            {
                if (EnvironmentProbe.IsMono)
                {
                    AddDefaultMonoHeaders();
                }
                else
                {
                    AddDefaultDotnetHeaders();
                }
            }

            return(sortedHeaders);
        }
Exemplo n.º 31
0
        private bool RequestIdInHeaders(RequestId.RequestId requestId, HttpRequestHeaders headers)
        {
            IEnumerable <string> value;

            return(headers.TryGetValues(requestId.RequestIdKey, out value));
        }
Exemplo n.º 32
0
 public HeaderHandler(HttpRequestHeaders headers)
 {
     _headers = headers;
 }
Exemplo n.º 33
0
 private bool ShouldAddRequestId(RequestId.RequestId requestId, HttpRequestHeaders headers)
 {
     return(!string.IsNullOrEmpty(requestId?.RequestIdKey) &&
            !string.IsNullOrEmpty(requestId.RequestIdValue) &&
            !RequestIdInHeaders(requestId, headers));
 }