async Task SetHeadersAndContent()

in edge-util/src/Microsoft.Azure.Devices.Edge.Util/uds/HttpRequestResponseSerializer.cs [71:127]


        async Task SetHeadersAndContent(HttpResponseMessage httpResponse, HttpBufferedStream bufferedStream, CancellationToken cancellationToken)
        {
            IList<string> headers = new List<string>();
            string line = await bufferedStream.ReadLineAsync(cancellationToken);
            while (!string.IsNullOrWhiteSpace(line))
            {
                headers.Add(line);
                line = await bufferedStream.ReadLineAsync(cancellationToken);
            }

            httpResponse.Content = new StreamContent(bufferedStream);
            var contentHeaders = new Dictionary<string, string>();
            foreach (string header in headers)
            {
                if (string.IsNullOrWhiteSpace(header))
                {
                    // headers end
                    break;
                }

                int headerSeparatorPosition = header.IndexOf(HeaderSeparator);
                if (headerSeparatorPosition <= 0)
                {
                    throw new HttpRequestException($"Header is invalid {header}.");
                }

                string headerName = header.Substring(0, headerSeparatorPosition).Trim();
                string headerValue = header.Substring(headerSeparatorPosition + 1).Trim();

                bool headerAdded = httpResponse.Headers.TryAddWithoutValidation(headerName, headerValue);
                if (!headerAdded)
                {
                    contentHeaders.Add(headerName, headerValue);
                }
            }

            bool isChunked = httpResponse.Headers.TransferEncodingChunked.HasValue
                             && httpResponse.Headers.TransferEncodingChunked.Value;

            httpResponse.Content = isChunked
                ? new StreamContent(new HttpChunkedStreamReader(bufferedStream))
                : new StreamContent(bufferedStream);

            foreach (KeyValuePair<string, string> contentHeader in contentHeaders)
            {
                httpResponse.Content.Headers.TryAddWithoutValidation(contentHeader.Key, contentHeader.Value);
                if (string.Equals(contentHeader.Key, ContentLengthHeaderName, StringComparison.InvariantCultureIgnoreCase))
                {
                    if (!long.TryParse(contentHeader.Value, out long contentLength))
                    {
                        throw new HttpRequestException($"Header value {contentHeader.Value} is invalid for {ContentLengthHeaderName}.");
                    }

                    await httpResponse.Content.LoadIntoBufferAsync(contentLength);
                }
            }
        }