/// <summary>
        /// Looks for the "start" parameter of the parent's content type and then finds the corresponding
        /// child HttpContent with a matching Content-ID header field.
        /// </summary>
        /// <returns>The matching child or null if none found.</returns>
        private static HttpContent FindRootContent(HttpContent parent, IEnumerable <HttpContent> children)
        {
            Contract.Assert(children != null);

            // Find 'start' parameter from parent content type. The value is used
            // to identify the MIME body with the corresponding Content-ID header value.
            NameValueHeaderValue startNameValue = FindMultipartRelatedParameter(parent, StartParameter);

            if (startNameValue == null)
            {
                // If we didn't find a "start" parameter then take the first child.
                return(children.FirstOrDefault());
            }

            // Look for the child with a Content-ID header that corresponds to the "start" value.
            // If no matching child is found then we return null.
            string startValue = FormattingUtilities.UnquoteToken(startNameValue.Value);

            return(children.FirstOrDefault(
                       content =>
            {
                IEnumerable <string> values;
                if (content.Headers.TryGetValues(ContentID, out values))
                {
                    return String.Equals(
                        FormattingUtilities.UnquoteToken(values.ElementAt(0)),
                        startValue,
                        StringComparison.OrdinalIgnoreCase);
                }

                return false;
            }));
        }
Exemple #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MimeBodyPart"/> class.
 /// </summary>
 /// <param name="streamProvider">The stream provider.</param>
 /// <param name="maxBodyPartHeaderSize">The max length of the MIME header within each MIME body part.</param>
 /// <param name="parentContent">The part's parent content</param>
 public MimeBodyPart(MultipartStreamProvider streamProvider, int maxBodyPartHeaderSize, HttpContent parentContent)
 {
     Contract.Assert(streamProvider != null);
     Contract.Assert(parentContent != null);
     this._streamProvider = streamProvider;
     this._parentContent  = parentContent;
     this.Segments        = new List <ArraySegment <byte> >(2);
     this._headers        = FormattingUtilities.CreateEmptyContentHeaders();
     this.HeaderParser    = new InternetMessageFormatHeaderParser(this._headers, maxBodyPartHeaderSize);
 }
Exemple #3
0
        /// <summary>
        /// Validates whether the content contains an HTTP Request or an HTTP Response.
        /// </summary>
        /// <param name="content">The content to validate.</param>
        /// <param name="isRequest">if set to <c>true</c> if the content is either an HTTP Request or an HTTP Response.</param>
        /// <param name="throwOnError">Indicates whether validation failure should result in an <see cref="Exception"/> or not.</param>
        /// <returns><c>true</c> if content is either an HTTP Request or an HTTP Response</returns>
        internal static bool ValidateHttpMessageContent(HttpContent content, bool isRequest, bool throwOnError)
        {
            if (content == null)
            {
                throw Error.ArgumentNull("content");
            }

            MediaTypeHeaderValue contentType = content.Headers.ContentType;

            if (contentType != null)
            {
                if (!contentType.MediaType.Equals(DefaultMediaType, StringComparison.OrdinalIgnoreCase))
                {
                    if (throwOnError)
                    {
                        throw Error.Argument("content", Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name,
                                             isRequest ? DefaultRequestMediaType : DefaultResponseMediaType);
                    }
                    else
                    {
                        return(false);
                    }
                }

                foreach (NameValueHeaderValue parameter in contentType.Parameters)
                {
                    if (parameter.Name.Equals(MsgTypeParameter, StringComparison.OrdinalIgnoreCase))
                    {
                        string msgType = FormattingUtilities.UnquoteToken(parameter.Value);
                        if (!msgType.Equals(isRequest ? DefaultRequestMsgType : DefaultResponseMsgType, StringComparison.OrdinalIgnoreCase))
                        {
                            if (throwOnError)
                            {
                                throw Error.Argument("content", Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name, isRequest ? DefaultRequestMediaType : DefaultResponseMediaType);
                            }
                            else
                            {
                                return(false);
                            }
                        }

                        return(true);
                    }
                }
            }

            if (throwOnError)
            {
                throw Error.Argument("content", Resources.HttpMessageInvalidMediaType, FormattingUtilities.HttpContentType.Name, isRequest ? DefaultRequestMediaType : DefaultResponseMediaType);
            }
            else
            {
                return(false);
            }
        }
        /// <summary>
        /// Copies the unsorted header fields to a sorted collection.
        /// </summary>
        /// <param name="source">The unsorted source headers</param>
        /// <param name="destination">The destination <see cref="HttpRequestHeaders"/> or <see cref="HttpResponseHeaders"/>.</param>
        /// <param name="contentStream">The input <see cref="Stream"/> used to form any <see cref="HttpContent"/> being part of this HTTP request.</param>
        /// <param name="rewind">Start location of any request entity within the <paramref name="contentStream"/>.</param>
        /// <returns>An <see cref="HttpContent"/> instance if header fields contained and <see cref="HttpContentHeaders"/>.</returns>
        private static HttpContent CreateHeaderFields(HttpHeaders source, HttpHeaders destination, Stream contentStream, int rewind)
        {
            Contract.Assert(source != null, "source headers cannot be null");
            Contract.Assert(destination != null, "destination headers cannot be null");
            Contract.Assert(contentStream != null, "contentStream must be non null");
            HttpContentHeaders contentHeaders = null;
            HttpContent        content        = null;

            // Set the header fields
            foreach (KeyValuePair <string, IEnumerable <string> > header in source)
            {
                if (!destination.TryAddWithoutValidation(header.Key, header.Value))
                {
                    if (contentHeaders == null)
                    {
                        contentHeaders = FormattingUtilities.CreateEmptyContentHeaders();
                    }

                    contentHeaders.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            // If we have content headers then create an HttpContent for this Response
            if (contentHeaders != null)
            {
                // Need to rewind the input stream to be at the position right after the HTTP header
                // which we may already have parsed as we read the content stream.
                if (!contentStream.CanSeek)
                {
                    throw Error.InvalidOperation(Resources.HttpMessageContentStreamMustBeSeekable, "ContentReadStream", FormattingUtilities.HttpResponseMessageType.Name);
                }

                contentStream.Seek(0 - rewind, SeekOrigin.Current);
                content = new StreamContent(contentStream);
                contentHeaders.CopyTo(content.Headers);
            }

            return(content);
        }
        /// <summary>
        /// Read the non-file contents as form data.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the post processing.</returns>
        public static async Task ReadFormDataAsync(Collection <HttpContent> contents,
                                                   NameValueCollection formData, CancellationToken cancellationToken)
        {
            // Find instances of HttpContent for which we created a memory stream and read them asynchronously
            // to get the string content and then add that as form data
            foreach (HttpContent content in contents)
            {
                ContentDispositionHeaderValue contentDisposition = content.Headers.ContentDisposition;
                // If FileName is null or empty, the content is form data and will be processed.
                if (String.IsNullOrEmpty(contentDisposition.FileName))
                {
                    // Extract name from Content-Disposition header. We know from earlier that the header is present.
                    string formFieldName = FormattingUtilities.UnquoteToken(contentDisposition.Name) ?? String.Empty;

                    // Read the contents as string data and add to form data
                    cancellationToken.ThrowIfCancellationRequested();
                    string formFieldValue = await content.ReadAsStringAsync();

                    formData.Add(formFieldName, formFieldValue);
                }
            }
        }