示例#1
0
        public virtual async Task <IList <HttpRequestMessage> > ParseBatchRequestsAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken
            )
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            List <HttpRequestMessage> requests = new List <HttpRequestMessage>();

            cancellationToken.ThrowIfCancellationRequested();
            MultipartStreamProvider streamProvider = await request.Content.ReadAsMultipartAsync();

            foreach (HttpContent httpContent in streamProvider.Contents)
            {
                cancellationToken.ThrowIfCancellationRequested();
                HttpRequestMessage innerRequest =
                    request.RequestUri == null
                        ? await httpContent.ReadAsHttpRequestMessageAsync()
                        : await httpContent.ReadAsHttpRequestMessageAsync(
                        request.RequestUri.Scheme
                        );

                innerRequest.CopyBatchRequestProperties(request);
                requests.Add(innerRequest);
            }
            return(requests);
        }
 /// <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);
 }
        public async Task<object> ToObjectAsync(MultipartStreamProvider provider, Type type)
        {
            var contents = provider.Contents;
            var textContents = contents.Where(p => string.IsNullOrWhiteSpace(p.Headers.ContentDisposition.FileName));
            var fileContents = contents.Except(textContents);
            var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);

            object obj = await ParseHttpContentToObjectAsync(type, textContents);

            await SetFilePropertiesAsync(fileContents, properties, obj);

            return obj;
        }
示例#4
0
        static async Task SaveAssembledDocuments(HttpResponseMessage response)
        {
            MultipartStreamProvider multipartStream = await response.Content.ReadAsMultipartAsync();

            foreach (var attachment in multipartStream.Contents)
            {
                Stream writeAttachmentStream = await attachment.ReadAsStreamAsync();

                using (FileStream output = new FileStream(@"C:\temp\" + attachment.Headers.ContentDisposition.FileName, FileMode.Create))
                {
                    writeAttachmentStream.CopyTo(output);
                }
            }
        }
        public async Task BatchRequest_SubRequestPropertiesDoNotContainRoutingContext_CopyProperties()
        {
            // Arrange
            const string      baseAddress = "http://localhost/api/";
            HttpConfiguration config      = new HttpConfiguration();
            HttpServer        server      = new HttpServer(config);

            config.Routes.MapHttpBatchRoute(
                routeName: "Batch",
                routeTemplate: "api/$batch",
                batchHandler: new CustomHttpBatchHandler(server));
            config.Routes.MapHttpRoute(
                "Default",
                "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            // Act
            using (HttpClient client = new HttpClient(server))
                using (HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, baseAddress + "$batch"))
                {
                    batchRequest.Content = new MultipartContent("mixed")
                    {
                        new HttpMessageContent(
                            new HttpRequestMessage(HttpMethod.Post, baseAddress + "values")
                        {
                            Content = new ObjectContent <string>("newValue", new JsonMediaTypeFormatter())
                        }),
                        new HttpMessageContent(new HttpRequestMessage(HttpMethod.Get, baseAddress + "values/newValue"))
                    };

                    using (HttpResponseMessage batchResponse = await client.SendAsync(batchRequest, CancellationToken.None))
                    {
                        MultipartStreamProvider streamProvider = await batchResponse.Content.ReadAsMultipartAsync();

                        foreach (HttpContent content in streamProvider.Contents)
                        {
                            HttpResponseMessage response = await content.ReadAsHttpResponseMessageAsync();

                            string result = await response.Content.ReadAsStringAsync();

                            // Assert
                            Assert.Equal("\"newValue\"", result);
                        }
                    }
                }
        }
        public virtual async Task <IList <HttpRequestMessage> > ParseBatchRequestsAsync(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            List <HttpRequestMessage> requests       = new List <HttpRequestMessage>();
            MultipartStreamProvider   streamProvider = await request.Content.ReadAsMultipartAsync();

            foreach (HttpContent httpContent in streamProvider.Contents)
            {
                HttpRequestMessage innerRequest = await httpContent.ReadAsHttpRequestMessageAsync();

                requests.Add(innerRequest);
            }
            return(requests);
        }
示例#7
0
        static Task <Stream> ProcessBody(MultipartStreamProvider multipart)
        {
            var first = multipart.Contents.FirstOrDefault();

            if (first == null)
            {
                throw new("Expected the multipart response have at least one part which contains the GraphQL response data.");
            }

            var name = first.Headers.ContentDisposition?.Name;

            if (name == null)
            {
                throw new("Expected the first part in the multipart response to be named.");
            }

            return(first.ReadAsStreamAsync());
        }
示例#8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeMultipartBodyPartParser"/> class.
        /// </summary>
        /// <param name="content">An existing <see cref="HttpContent"/> instance to use for the object's content.</param>
        /// <param name="streamProvider">A stream provider providing output streams for where to write body parts as they are parsed.</param>
        /// <param name="maxMessageSize">The max length of the entire MIME multipart message.</param>
        /// <param name="maxBodyPartHeaderSize">The max length of the MIME header within each MIME body part.</param>
        public MimeMultipartBodyPartParser(
            HttpContent content,
            MultipartStreamProvider streamProvider,
            long maxMessageSize,
            int maxBodyPartHeaderSize)
        {
            Contract.Assert(content != null, "content cannot be null.");
            Contract.Assert(streamProvider != null, "streamProvider cannot be null.");

            string boundary = ValidateArguments(content, maxMessageSize, true);

            _mimeParser            = new MimeMultipartParser(boundary, maxMessageSize);
            _currentBodyPart       = new MimeBodyPart(streamProvider, maxBodyPartHeaderSize, content);
            _content               = content;
            _maxBodyPartHeaderSize = maxBodyPartHeaderSize;

            _streamProvider = streamProvider;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeMultipartBodyPartParser"/> class.
        /// </summary>
        /// <param name="content">An existing <see cref="HttpContent"/> instance to use for the object's content.</param>
        /// <param name="streamProvider">A stream provider providing output streams for where to write body parts as they are parsed.</param>
        /// <param name="maxMessageSize">The max length of the entire MIME multipart message.</param>
        /// <param name="maxBodyPartHeaderSize">The max length of the MIME header within each MIME body part.</param>
        public MimeMultipartBodyPartParser(
            HttpContent content,
            MultipartStreamProvider streamProvider,
            long maxMessageSize,
            int maxBodyPartHeaderSize)
        {
            Contract.Assert(content != null, "content cannot be null.");
            Contract.Assert(streamProvider != null, "streamProvider cannot be null.");

            string boundary = ValidateArguments(content, maxMessageSize, true);

            _mimeParser = new MimeMultipartParser(boundary, maxMessageSize);
            _currentBodyPart = new MimeBodyPart(streamProvider, maxBodyPartHeaderSize, content);
            _content = content;
            _maxBodyPartHeaderSize = maxBodyPartHeaderSize;

            _streamProvider = streamProvider;
        }
示例#10
0
文件: Batch.cs 项目: maskx/OData
        public void Success()
        {
            //TODO: Batch not support now
            HttpClient         client       = new HttpClient();
            HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, string.Format(Common.Tpl, "$batch"));

            AddRequest(batchRequest, HttpMethod.Get, string.Format(Common.Tpl, "Tag"));
            AddRequest(batchRequest, HttpMethod.Get, string.Format(Common.Tpl, "AspNetUsers"));
            var batchResponse = client.SendAsync(batchRequest).Result;
            MultipartStreamProvider streamProvider = batchResponse.Content.ReadAsMultipartAsync().Result;

            foreach (var content in streamProvider.Contents)
            {
                HttpResponseMessage response = content.ReadAsHttpResponseMessageAsync().Result;
                if (response.IsSuccessStatusCode)
                {
                    var b = response.Content.ToString();
                }
            }
        }
        private async Task <IDictionary <string, object> > ToModelDictionaryAsync(
            MultipartStreamProvider multipartProvider)
        {
            var dictionary = new Dictionary <string, object>();

            // iterate all parts
            foreach (var part in multipartProvider.Contents)
            {
                // unescape the name
                var name = part.Headers.ContentDisposition.Name.Trim('"');

                // if we have a filename, we treat the part as file upload,
                // otherwise as simple string, model binder will convert strings to other types.
                if (MultipartReducedMemoryStreamProvider.SuggestsFileContent(part.Headers))
                {
                    // set null if no content was submitted to have support for [Required]
                    if (part.Headers.ContentLength.GetValueOrDefault() > 0)
                    {
                        dictionary[name] = new HttpPostedFileMultipart(
                            part.Headers.ContentDisposition.FileName.Trim('"'),
                            part.Headers.ContentType?.MediaType,
                            await part.ReadAsStreamAsync()
                            );
                    }
                    else
                    {
                        dictionary[name] = null;
                    }
                }
                else
                {
                    dictionary[name] = await part.ReadAsStringAsync();
                }
            }

            return(dictionary);
        }
示例#12
0
        public override async Task <object> ReadFromStreamAsync(Type type, Stream stream,
                                                                HttpContent httpContent,
                                                                IFormatterLogger iFormatterLogger)
        {
            MultipartStreamProvider parts = await httpContent.ReadAsMultipartAsync();

            IEnumerable <HttpContent> contents = parts.Contents;

            HttpContent content = contents.FirstOrDefault();

            foreach (HttpContent c in contents)
            {
                if (SupportedMediaTypes.Contains(c.Headers.ContentType))
                {
                    content = c;
                    break;
                }
            }

            using (var msgStream = await content.ReadAsStreamAsync())
            {
                DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(TenMsg));
                TenMsg msg = (TenMsg)js.ReadObject(msgStream);
                Debug.WriteLine("msgString: " + msgStream.ToString());

                int      sender     = msg.Sender;
                int      receiver   = msg.Receiver;
                byte     phoneType  = msg.PhoneType;
                bool     isLocked   = msg.IsLocked;
                DateTime msgTime    = msg.MsgTime;
                string   msgContent = msg.MsgContent;
                Debug.WriteLine("Msg Content: " + msg.MsgContent);

                return(new TenMsg(sender, receiver, phoneType, isLocked, msgTime, msgContent));
            }
        }
示例#13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MimeMultipartBodyPartParser"/> class.
 /// </summary>
 /// <param name="content">An existing <see cref="HttpContent"/> instance to use for the object's content.</param>
 /// <param name="streamProvider">A stream provider providing output streams for where to write body parts as they are parsed.</param>
 public MimeMultipartBodyPartParser(HttpContent content, MultipartStreamProvider streamProvider)
     : this(content, streamProvider, DefaultMaxMessageSize, DefaultMaxBodyPartHeaderSize)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MimeMultipartBodyPartParser"/> class.
 /// </summary>
 /// <param name="content">An existing <see cref="HttpContent"/> instance to use for the object's content.</param>
 /// <param name="streamProvider">A stream provider providing output streams for where to write body parts as they are parsed.</param>
 public MimeMultipartBodyPartParser(HttpContent content, MultipartStreamProvider streamProvider)
     : this(content, streamProvider, DefaultMaxMessageSize, DefaultMaxBodyPartHeaderSize)
 {
 }