/// <summary>
        /// Formats the HTTP content as an asynchronous operation.
        /// </summary>
        /// <param name="sb">a <see cref="System.Text.StringBuilder"/>.</param>
        /// <param name="content">The content of the http message.</param>
        /// <returns>Task.</returns>
        public static async Task FormatHttpContentAsync(StringBuilder sb, HttpContent content)
        {
            if (content.Headers != null)
            {
                foreach (var header in content.Headers)
                {
                    sb.AppendLine(string.Format("{0} : {1}", header.Key, header.Value.First()));
                }
            }

            await content.LoadIntoBufferAsync().ConfigureAwait(false);

            bool isMultipart = content.IsMimeMultipartContent();

            if (isMultipart)
            {
                //TODO: for some reason it hangs when trying to read the multi-part.  might have something to do with UI thread :(

                //MultipartMemoryStreamProvider provider = await content.ReadAsMultipartAsync();

                //TODO: for now format just the first part.  We will need to figure out what to do with the remain
                //parts so that it doesnt break viewer
                //content = provider.Contents.First() as StreamContent;
            }
            var sw     = new StringWriter(sb);
            var writer = new JsonTextWriter(sw)
            {
                Formatting  = Formatting.Indented,
                Indentation = 4,
                IndentChar  = ' '
            };

            string contentBody = await content.ReadAsStringAsync().ConfigureAwait(false);

            try
            {
                var jsonSerializer = new JsonSerializer();
                var reader         = new JsonTextReader(new StringReader(contentBody));

                object obj = jsonSerializer.Deserialize(reader);
                if (obj != null)
                {
                    jsonSerializer.Serialize(writer, obj);
                }
                else
                {
                    sb.AppendLine(contentBody);
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine(contentBody);
                Logger.Instance.Warning("JsonWriter failed with ex: " + ex.ToString());
            }
            finally
            {
                writer.Close();
                sw.Close();
            }
        }
        /// <summary>
        /// Asynchronously deserialises an object of the specified type.
        /// </summary>
        ///
        /// <returns>
        /// A <see cref="T:System.Threading.Tasks.Task"/> whose result will be an object of the given type.
        /// </returns>
        /// <param name="type">The type of the object to deserialise.</param>
        /// <param name="readStream">The <see cref="T:System.IO.Stream"/> to read.</param>
        /// <param name="content">The <see cref="T:System.Net.Http.HttpContent"/>, if available. It may be null.</param>
        /// <param name="formatterLogger">The <see cref="T:System.Net.Http.Formatting.IFormatterLogger"/> to log events to.</param>
        /// <exception cref="T:HttpResponseException">Derived types need to support reading.</exception>
        public async override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            try
            {
                if (content.IsMimeMultipartContent())
                {
                    return(await ReadFromMultipartStreamAsync(content));
                }
                if (MediaTypeApplicationJson == content.Headers.ContentType?.MediaType)
                {
                    return(await ReadFromJsonStreamAsync(content));
                }
                if (MediaTypeTextXml == content.Headers.ContentType?.MediaType || MediaTypeApplicationXml == content.Headers.ContentType?.MediaType)
                {
                    return(await ReadFromXmlStreamAsync(content));
                }

                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            catch (Exception exception)
            {
                var msg = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(exception.ToString())
                };
                throw new HttpResponseException(msg);
            }
        }
        public async override Task <object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
        {
            try
            {
                if (!content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                var provider = await content.ReadAsMultipartAsync();

                var mediacontent = provider.Contents.First(x =>
                                                           SupportedMediaTypes.Contains(x.Headers.ContentType));

                string fileName = mediacontent.Headers.ContentDisposition.FileName;

                string mediaType = mediacontent.Headers.ContentType.MediaType;

                var imagebuffer = await mediacontent.ReadAsByteArrayAsync();

                return(new ImageMediaModels(fileName, mediaType, imagebuffer));
            }
            catch (Exception Ex)
            {
                string Err = "Unable to upload the image ";
                Log.LogError("{0}, Error: {1}", Err, Ex.Message);
                throw;
            }
        }
示例#4
0
    public async override Task <object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger logger)
    {
        if (!content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var provider = new MultipartMemoryStreamProvider();
        var formData = await content.ReadAsMultipartAsync(provider);

        var imageContent = formData.Contents
                           .Where(c => SupportedMediaTypes.Contains(c.Headers.ContentType))
                           .Select(i => ReadContent(i).Result)
                           .ToList();

        var jsonContent = formData.Contents
                          .Where(c => !SupportedMediaTypes.Contains(c.Headers.ContentType))
                          .Select(j => ReadJson(j).Result)
                          .ToDictionary(x => x.Key, x => x.Value);

        var json  = JsonConvert.SerializeObject(jsonContent);
        var model = JsonConvert.DeserializeObject(json, type) as ImageContentList;

        if (model == null)
        {
            throw new HttpResponseException(HttpStatusCode.NoContent);
        }

        model.Images = imageContent;
        return(model);
    }
示例#5
0
        //REF: http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/
        private async Task <string> RetrieveJsonFromRequest(HttpContent content)
        {
            if (!content.IsMimeMultipartContent())
            {
                return(await content.ReadAsStringAsync());
            }

            var provider = LoadMultipartStreamProvider();
            var result   = await content.ReadAsMultipartAsync(provider);

            return(MapFilePathsToCommandJson(result));
        }
        public override async Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (content.IsMimeMultipartContent() == false)
            {
                return(null);
            }
            var provider = await content.ReadAsMultipartAsync();

            var converter = new MultipartStreamConverter(formatterLogger);

            return(await converter.ToObjectAsync(provider, type));
        }
示例#7
0
        public static async Task <TResult> ParseMultipartAsync_ <TMethod, TResult>(this HttpContent content,
                                                                                   Expression <TMethod> callback)
        {
            if (!content.IsMimeMultipartContent())
            {
                throw new ArgumentException("Content is not multipart", "content");
            }

            var streamProvider = new MultipartMemoryStreamProvider();
            await content.ReadAsMultipartAsync(streamProvider);

            var paramTasks = callback.Parameters.Select(
                async(param) =>
            {
                var paramContent = streamProvider.Contents.FirstOrDefault(file => file.Headers.ContentDisposition.Name.Contains(param.Name));
                if (default(HttpContent) == paramContent)
                {
                    return(param.Type.IsValueType ? Activator.CreateInstance(param.Type) : null);
                }

                if (param.Type.GUID == typeof(string).GUID)
                {
                    var stringValue = await paramContent.ReadAsStringAsync();
                    return((object)stringValue);
                }
                if (param.Type.GUID == typeof(long).GUID)
                {
                    var guidStringValue = await paramContent.ReadAsStringAsync();
                    var guidValue       = long.Parse(guidStringValue);
                    return((object)guidValue);
                }
                if (param.Type.GUID == typeof(System.IO.Stream).GUID)
                {
                    var streamValue = await paramContent.ReadAsStreamAsync();
                    return((object)streamValue);
                }
                if (param.Type.GUID == typeof(byte[]).GUID)
                {
                    var byteArrayValue = await paramContent.ReadAsByteArrayAsync();
                    return((object)byteArrayValue);
                }
                var value = await paramContent.ReadAsAsync(param.Type);
                return(value);
            });

            var paramsForCallback = await Task.WhenAll(paramTasks);

            var result = ((LambdaExpression)callback).Compile().DynamicInvoke(paramsForCallback);

            return((TResult)result);
        }
示例#8
0
        public async Task <Response <string> > UploadImageToAzure(HttpContent request)
        {
            try
            {
                string[] _supportedMimeTypes = { "image/png", "image/jpeg", "image/jpg" };
                var      httprequest         = HttpContext.Current.Request;
                if (!request.IsMimeMultipartContent("form-data"))
                {
                    return(new Response <string>()
                    {
                        StatusCode = System.Net.HttpStatusCode.UnsupportedMediaType
                    });
                }
                GetStorageReference();

                var provider = new AzureStorageMultipartFormDataStreamProvider(blobContainer);

                try
                {
                    await request.ReadAsMultipartAsync(provider);
                }
                catch (Exception ex)
                {
                    return(new Response <string>()
                    {
                        StatusCode = System.Net.HttpStatusCode.BadRequest, Message = $"An error has occured.Details: { ex.Message}"
                    });
                }

                var storagePath = ConfigurationManager.AppSettings["storagePath"];
                // Retrieve the filename of the file you have uploaded
                var filename = provider.FileData.FirstOrDefault()?.LocalFileName;
                var filePath = string.Concat(storagePath, filename);
                if (string.IsNullOrEmpty(filename))
                {
                    return(new Response <string>()
                    {
                        StatusCode = System.Net.HttpStatusCode.BadRequest, Message = "An error has occured while uploading your file. Please try again."
                    });
                }
                return(new Response <string>()
                {
                    StatusCode = HttpStatusCode.OK, Message = $"{filePath}"
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (!content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var directory = Path.GetTempPath();
            var provider  = new MultipartFormDataStreamProvider(directory);

            return(content.ReadAsMultipartAsync(provider).ContinueWith(t => {
                var file = provider.FileData.First();
                var filename = Path.GetFileName(file.Headers.ContentDisposition.FileName.Trim('"'));

                return new MediaFileData(File.ReadAllBytes(file.LocalFileName), file.Headers.ContentType.MediaType, filename) as object;
            }));
        }
示例#10
0
        public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            if (!content.IsMimeMultipartContent())
            {
                throw new Exception("Unsupported Media Type");
            }

            var provider = Task.Run(() => content.ReadAsMultipartAsync()).GetAwaiter().GetResult();

            var jsonContent = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.Replace("\"", string.Empty)
                                                               .Equals("Data", StringComparison.OrdinalIgnoreCase));
            var imageModel = jsonContent != null?JsonConvert.DeserializeObject <ImageModel>(jsonContent.ReadAsStringAsync().Result) : new ImageModel();

            foreach (var dataSection in provider.Contents.Where(c => !string.IsNullOrEmpty(c.Headers.ContentDisposition.FileName)))
            {
                var sectionName = dataSection.Headers.ContentDisposition.Name.Replace("\"", string.Empty);
                var fileName    = dataSection.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
                if (fileName.Contains("\\"))
                {
                    fileName = Path.GetFileName(fileName);
                }

                var mediaType = dataSection.Headers.ContentType.MediaType;

                var data = dataSection.ReadAsByteArrayAsync().GetAwaiter().GetResult();

                switch (sectionName.ToUpperInvariant())
                {
                case "ANNOTATION":
                    imageModel.AnnotationFileModel = new HttpFileModel(fileName, mediaType, data);
                    break;

                case "IMAGE":
                    imageModel.ImageFileModel = new HttpFileModel(fileName, mediaType, data);
                    break;
                }
            }

            return(imageModel);
        }
示例#11
0
        /// <summary>载入上传的第一个文件流</summary>
        public static async Task ReadFileStreamFirstOrDefault(this HttpContent httpContent, IFileUploadRequest request, string rootPath)
        {
            if (!httpContent.IsMimeMultipartContent())
            {
                return;
            }
            var provider = await httpContent.ReadAsMultipartAsync(new MultipartFileStreamProvider(rootPath));

            var fileData = provider.FileData.FirstOrDefault();

            if (fileData == null)
            {
                return;
            }
            request.FileName    = fileData.Headers.ContentDisposition.FileName;
            request.ContentType = fileData.Headers.ContentType.ToString();
            request.ServerFile  = fileData.LocalFileName;
        }
        public async Task <FormData> Convert(HttpContent content)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            if (!content.IsMimeMultipartContent())
            {
                throw new Exception("Unsupported Media Type");
            }

            MultipartMemoryStreamProvider multipartProvider = await content.ReadAsMultipartAsync();

            var multipartFormData = await Convert(multipartProvider);

            return(multipartFormData);
        }
示例#13
0
        public async override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (!content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var response = await content.ReadAsMultipartAsync();

            var fileContent = response.Contents.Where(x => x.Headers.ContentDisposition.Name.Trim('"') == "document");
            var jsonContent = response.Contents.Where(x => x.Headers.ContentDisposition.Name.Trim('"') == "json").FirstOrDefault();
            var jsonData    = await jsonContent.ReadAsStringAsync();

            var document = JsonConvert.DeserializeObject <Document>(jsonData);

            document.Content = fileContent;
            return(document);
        }
示例#14
0
        public override async Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            object result = null;

            if (content.IsMimeMultipartContent())
            {
                var multipart = await content.ReadAsMultipartAsync();

                foreach (var item in multipart.Contents)
                {
                    var data = await item.ReadAsByteArrayAsync();

                    result = new FileData(item.Headers.ContentDisposition.FileName.Replace("\"", ""), data);
                }
            }

            return(result);
        }
        public override Task <object> ReadFromStreamAsync(Type type,
                                                          Stream readStream,
                                                          HttpContent content,
                                                          IFormatterLogger formatterLogger)
        {
            if (!content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var parts = content.ReadAsMultipartAsync();

            return(Task.Factory.StartNew(() =>
            {
                object data = null;
                var valueCollection = new List <KeyValuePair <string, string> >();
                foreach (var partContent in parts.Result.Contents)
                {
                    if (partContent.Headers.ContentType == null)
                    {
                        var value = partContent.ReadAsStringAsync().Result;
                        var name = partContent.Headers.ContentDisposition.Name;
                        name = name.Substring(1, name.Length - 2);
                        valueCollection.Add(new KeyValuePair <string, string>(name, value));
                    }
                    else if (partContent.Headers.ContentType != null &&
                             partContent.Headers.ContentType.MediaType == "application/json")
                    {
                        var partBody = partContent.ReadAsStringAsync().Result;
                        data = JsonConvert.DeserializeObject(partBody, type);
                        break;
                    }
                }
                if (data == null)
                {
                    if (valueCollection.Count > 0)
                    {
                        data = new FormDataCollection(valueCollection).ConvertToObject(type);
                    }
                }
                return data;
            }));
        }
        /// <summary>
        /// Looks for a parameter in the <see cref="MediaTypeHeaderValue"/>.
        /// </summary>
        /// <returns>The matching parameter or null if none found.</returns>
        private static NameValueHeaderValue FindMultipartRelatedParameter(HttpContent content, string parameterName)
        {
            // If no parent then we are done
            if (content == null)
            {
                return(null);
            }

            // Check that we have a parent content type and that it is indeed multipart/related
            MediaTypeHeaderValue parentContentType = content.Headers.ContentType;

            if (parentContentType == null || !content.IsMimeMultipartContent(RelatedSubType))
            {
                return(null);
            }

            // Look for parameter
            return(parentContentType.Parameters.FirstOrDefault(nvp => String.Equals(nvp.Name, parameterName, StringComparison.OrdinalIgnoreCase)));
        }
        /// <param name="type">The type of the object to deserialize.</param>
        /// <param name="readStream">The <see cref="T:System.IO.Stream"/> to read.</param>
        /// <param name="content">The <see cref="T:System.Net.Http.HttpContent"/>, if available. It may be null.</param>
        /// <param name="formatterLogger">The <see cref="T:System.Net.Http.Formatting.IFormatterLogger"/> to log events to.</param>
        /// <returns>A <see cref="T:System.Threading.Tasks.Task"/> whose result will be an object of the given type.</returns>
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (!CanReadType(type))
            {
                throw new InvalidOperationException();
            }

            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            if (!content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            try
            {
                return(ReadFormDataAsync(content));
            }
            catch (Exception e)
            {
                if (formatterLogger == null)
                {
                    throw;
                }

                formatterLogger.LogError(string.Empty, e);
#if WEB_API2
                return(Task.FromResult <object>(new InputParameters()));
#else  // ASP.NET Web API 1
                var tcs = new TaskCompletionSource <object>();
                tcs.SetResult(new InputParameters());
                return(tcs.Task);
#endif
            }
        }
        public override async Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            content.Headers.ContentType = ParseContentType(content);

            if (!content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var multipartStream = await FixIncompleteMultipartContent(content);

            content = ReplaceContent(content, multipartStream);

            var streamProvider = CreateStreamProvider();
            await content.ReadAsMultipartAsync(streamProvider);

            await streamProvider.ExecutePostProcessingAsync();

            return(await ReadFormDataFromStreamAsync(streamProvider));
        }
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,
                                                          IFormatterLogger formatterLogger)
        {
            if (content.IsMimeMultipartContent())
            {
                var provider = GetMultipartProvider();

                try {
                    content.ReadAsMultipartAsync(provider);

                    object uploadData = GetFormData(type, provider);

                    return(Task.FromResult(uploadData));
                }
                catch (Exception e) {
                    formatterLogger.LogError(e.Message, e);
                }
            }

            return(base.ReadFromStreamAsync(type, readStream, content, formatterLogger));
        }
示例#20
0
        public static async Task <ListImportFileModel> GetFileFromContent(HttpContent httpcontent)
        {
            if (!httpcontent.IsMimeMultipartContent())
            {
                throw new InvalidOperationException();
            }

            var provider = new MultipartMemoryStreamProvider();
            await httpcontent.ReadAsMultipartAsync(provider);

            ListImportFileModel fileModel = new ListImportFileModel();

            foreach (var content in provider.Contents)
            {
                var file      = content;
                var paramName = file.Headers.ContentDisposition.Name.Trim('\"');
                var buffer    = await file.ReadAsByteArrayAsync();

                var stream = new MemoryStream(buffer);

                using (var s = new StreamReader(stream))
                {
                    switch (paramName)
                    {
                    case "file":
                        stream.CopyTo(fileModel.Stream);
                        fileModel.FileName = file.Headers.ContentDisposition.FileName.Trim('\"');
                        stream.Seek(0, SeekOrigin.Begin);
                        fileModel.Contents = s.ReadToEnd();
                        break;

                    case "options":
                        // Figure out what to do here
                        fileModel = Newtonsoft.Json.JsonConvert.DeserializeObject <ListImportFileModel>(s.ReadToEnd());
                        break;
                    }
                }
            }
            return(fileModel);
        }
示例#21
0
        public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            if (!content.IsMimeMultipartContent())
            {
                throw new Exception("Not a Multipart Content");
            }

            var boudaryParameter = content.Headers.ContentType.Parameters.FirstOrDefault(m => m.Name == "boundary" && !String.IsNullOrWhiteSpace(m.Value));

            if (boudaryParameter == null)
            {
                throw new Exception("multipart boundary not found");
            }

            var objectToMultipartDataByteArrayConverter = new ObjectToMultipartDataByteArrayConverter(Settings);

            byte[] multipartData = objectToMultipartDataByteArrayConverter.Convert(value, boudaryParameter.Value);

            await writeStream.WriteAsync(multipartData, 0, multipartData.Length);

            content.Headers.ContentLength = multipartData.Length;
        }
示例#22
0
        /// <summary>
        /// Сохранение, полученного от пользователя, файла
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task <string> SaveAsync(HttpContent content)
        {
            if (content == null || !content.IsMimeMultipartContent())
            {
                return(string.Empty);
            }

            var provider = new MultipartMemoryStreamProvider();
            await content.ReadAsMultipartAsync(provider);

            if (provider.Contents.Count == 0)
            {
                return(string.Empty);
            }

            try
            {
                var file   = provider.Contents[0];
                var buffer = await file.ReadAsByteArrayAsync();

                var guid = Guid.NewGuid().ToString();

                var filePath = Path.Combine(_path, guid);
                using (var localFile = new FileStream(filePath, FileMode.Create))
                {
                    await localFile.WriteAsync(buffer, 0, buffer.Length);

                    await localFile.FlushAsync();

                    localFile.Close();
                }
                return(guid);
            }
            catch
            {
                return(string.Empty);
            }
        }
示例#23
0
        /// <summary>The get entity with image model.</summary>
        /// <param name="serverMapPath">The server map path.</param>
        /// <param name="httpContent">The http content.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        /// <exception cref="HttpResponseException"></exception>
        private async Task <EntityWithImageModel <Entity> > GetEntityWithImageModel(string serverMapPath, HttpContent httpContent)
        {
            if (!httpContent.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var root = HttpContext.Current.Server.MapPath(serverMapPath);

            Directory.CreateDirectory(root);

            var provider = new MultipartFormDataStreamProvider(root);

            var taskEntityWithImageModel = await httpContent.ReadAsMultipartAsync(provider).ContinueWith <IEnumerable <EntityWithImageModel <Entity> > >(
                t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }

                var entityWithImageModel = new EntityWithImageModel <Entity>();
                FileInfo info;
                var fileData = provider.FileData.Select(
                    i =>
                {
                    info          = new FileInfo(i.LocalFileName);
                    var imageByte = File.ReadAllBytes(info.FullName);
                    entityWithImageModel.EntityModel     = this.MappingEntityWithImageModel(provider.FormData);
                    entityWithImageModel.FileDescription = new FileDescription(info.Name, info.FullName, info.Length / 1024, imageByte);
                    return(entityWithImageModel);
                });

                return(fileData);
            });

            return(taskEntityWithImageModel.FirstOrDefault());
        }
示例#24
0
        public static async Task <string> GetBodyText(HttpContent content)
        {
            if (content == null)
            {
                return("(empty body)");
            }

            if (content.IsMimeMultipartContent())
            {
                Stream stream = await content.ReadAsStreamAsync().ConfigureAwait(false);

                if (!stream.CanSeek)
                {
                    return("(cannot log body because HTTP stream cannot seek)");
                }

                StringBuilder multipartBodyBuilder           = new StringBuilder();
                MultipartMemoryStreamProvider streamProvider = new MultipartMemoryStreamProvider();
                await content.ReadAsMultipartAsync <MultipartMemoryStreamProvider>(streamProvider, (int)stream.Length).ConfigureAwait(false);

                try
                {
                    foreach (var multipartContent in streamProvider.Contents)
                    {
                        multipartBodyBuilder.AppendLine("-- beginning of multipart content --");

                        // Headers
                        string headerText = GetHeadersText(multipartContent.Headers);
                        multipartBodyBuilder.AppendLine(headerText);

                        // Body of message
                        string multipartBody = await multipartContent.ReadAsStringAsync().ConfigureAwait(false);

                        string formattedJsonBody;

                        if (TryFormatJsonBody(multipartBody, out formattedJsonBody))
                        {
                            multipartBody = formattedJsonBody;
                        }

                        if (String.IsNullOrWhiteSpace(multipartBody))
                        {
                            multipartBodyBuilder.AppendLine("(empty body)");
                        }
                        else
                        {
                            multipartBodyBuilder.AppendLine(multipartBody);
                        }

                        multipartBodyBuilder.AppendLine("-- end of multipart content --");
                    }
                }
                finally
                {
                    // Reset the stream position so consumers of this class can re-read the multipart content.
                    stream.Position = 0;
                }

                return(multipartBodyBuilder.ToString());
            }
            else
            {
                string body = await content.ReadAsStringAsync().ConfigureAwait(false);

                string formattedJsonBody;
                if (TryFormatJsonBody(body, out formattedJsonBody))
                {
                    body = formattedJsonBody;
                }

                if (String.IsNullOrWhiteSpace(body))
                {
                    return("(empty body)");
                }

                return(body);
            }
        }