Exemplo n.º 1
1
        public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {

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

            var Parts = await content.ReadAsMultipartAsync();
            var FileContent = Parts.Contents.First(x =>
                SupportedMediaTypes.Contains(x.Headers.ContentType));

            var DataString = "";
            foreach (var Part in Parts.Contents.Where(x => x.Headers.ContentDisposition.DispositionType == "form-data"
                                                        && x.Headers.ContentDisposition.Name == "\"data\""))
            {
                var Data = await Part.ReadAsStringAsync();
                DataString = Data;
            }

            string FileName = FileContent.Headers.ContentDisposition.FileName;
            string MediaType = FileContent.Headers.ContentType.MediaType;

            using (var Imgstream = await FileContent.ReadAsStreamAsync())
            {
                return new GenericContent { ContentType = MediaType, Body = ReadToEnd(Imgstream) };
            }
        }
Exemplo n.º 2
0
        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;
            }
                   
        }
Exemplo n.º 3
0
        public void IsMimeMultipartContentThrowsOnNullString(string boundary)
        {
            HttpContent content = CreateContent(boundary);

            Assert.NotNull(content);
            foreach (var subtype in CommonUnitTestDataSets.EmptyStrings)
            {
                Assert.ThrowsArgumentNull(() =>
                {
                    content.IsMimeMultipartContent(subtype);
                }, "subtype");
            }
        }
 /// <summary>
 /// Reads a file stream asynchronously.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <returns>A key/value pair that contains the name of the file with a stream value.</returns>
 /// <exception cref="System.Web.Http.HttpResponseException">
 /// </exception>
 public static async Task <FileStreamContent> ReadAsFileStreamAsync(this HttpContent content, CancellationToken cancellationToken)
 {
     if (content.IsMimeMultipartContent("form-data"))
     {
         content = (await content.ReadAsMultipartAsync(cancellationToken)).Contents.FirstOrDefault();
     }
     if (content == null || string.IsNullOrEmpty(content.Headers.ContentDisposition.FileName))
     {
         throw new HttpResponseException(HttpStatusCode.BadRequest);
     }
     return(new FileStreamContent(
                content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty),
                await content.ReadAsStreamAsync()));
 }
        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;
        }
Exemplo n.º 6
0
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            if (!content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var taskCompletionSource = new TaskCompletionSource<object>();
            content.ReadAsMultipartAsync().ContinueWith(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);

                var fileContents = t.Result.Contents.Where(x => SupportedMediaTypes.Contains(x.Headers.ContentType))
                    .ToArray();
                if (!fileContents.Any())
                {
                    taskCompletionSource.SetResult(null);
                }
                else
                {
                    var fileMedias = new List<FileMedia>();
                    foreach (var fileContent in fileContents)
                    {
                        var fileName = fileContent.Headers.ContentDisposition.FileName;
                        var mediaType = fileContent.Headers.ContentType.MediaType;

                        using (var imgStream = fileContent.ReadAsStreamAsync().Result)
                        {
                            var imageBuffer = imgStream.ReadFully();
                            var result = new FileMedia(fileName, mediaType, imageBuffer);
                            fileMedias.Add(result);
                        }
                    }

                    if (fileMedias.Count == 1)
                    {
                        taskCompletionSource.SetResult(fileMedias.Single());
                    }
                    else
                    {
                        taskCompletionSource.SetResult(fileMedias);
                    }
                }
            });

            return taskCompletionSource.Task;
        }
        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();
                byte[] multipartData = objectToMultipartDataByteArrayConverter.Convert(value, boudaryParameter.Value);

                await writeStream.WriteAsync (multipartData, 0, multipartData.Length);
                
                content.Headers.ContentLength = multipartData.Length;
        }
Exemplo n.º 8
0
        /// <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)));
        }
        public override Task<object> ReadFromStreamAsync(Type type,
            Stream readStream,
            HttpContent content,
            IFormatterLogger formatterLogger)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            //if (readStream == null)
            //    throw new ArgumentNullException("readStream");

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

            var retValue = content.ReadAsMultipartAsync().ContinueWith<object>(t => RetrieveMediaPart(t));

            return retValue;
        }
        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);
        }
Exemplo n.º 11
0
        public override Task<object> ReadFromStreamAsync(Type type, System.IO.Stream readStream, HttpContent content, System.Net.Http.Formatting.IFormatterLogger formatterLogger)
        {
            if (!content.IsMimeMultipartContent())
            {
                throw new System.Web.Http.HttpResponseException(System.Net.HttpStatusCode.UnsupportedMediaType);
            }

            var parts = content.ReadAsMultipartAsync();
            return Task.Factory.StartNew<object>(() =>
            {
                object data = null;
                List<KeyValuePair<string, string>> 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);
                        //var valueCollectionJson = valueCollection.ToJson();
                        //data = JsonConvert.DeserializeObject(valueCollectionJson, type);
                    }
                }
                return data;
            });
        }
Exemplo n.º 12
0
        private async Task<string> UploadAnyFileAsync(
            HttpContent httpContent, 
            string[] allowedExtensions, 
            string folderPath)
        {
            if (!httpContent.IsMimeMultipartContent("form-data"))
            {
                throw new NotSupportedException();
            }

            var provider = new CustomMultipartStreamProvider(folderPath);
            await httpContent.ReadAsMultipartAsync(provider);
            var fullFileName = provider.FileData.First().LocalFileName;
            var extension = GetFileExtension(fullFileName);
            if (!allowedExtensions.Contains(extension))
            {
                await Task.Factory.StartNew(() => File.Delete(fullFileName));
                throw new InvalidDataException("Extension {0} is not allowed".FormatString(extension)); 
            }

            return fullFileName;
        }
Exemplo n.º 13
0
        public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content,
            IFormatterLogger formatterLogger,
            CancellationToken cancellationToken)

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

            var fileDto = new FileDto();
            var parts = await content.ReadAsMultipartAsync(cancellationToken);
            //file content
            var fileContent = parts.Contents.FirstOrDefault(x => x.Headers.ContentDisposition.Name == "\"file\"");
            //file information
            var data = parts.Contents.FirstOrDefault(x => x.Headers.ContentDisposition.Name == "\"data\"");
            var dataStr = await data.ReadAsStringAsync();
            fileDto = JsonConvert.DeserializeObject<FileDto>(dataStr);

            fileDto.File = await fileContent.ReadAsStreamAsync();

            return fileDto;

        }
        /// <summary>
        /// Upload a file sent in an http request
        /// </summary>
        /// <param name="httpContent">request's content</param>
        /// <returns>Error message or null</returns>
        private async Task<String> AddFormatFromHttpContent(HttpContent httpContent, DocumentFormat format)
        {
            if (httpContent == null || !httpContent.IsMimeMultipartContent())
                return "Attachment not found!";

            var provider = await httpContent.ReadAsMultipartAsync(
                new FormatStoreMultipartStreamProvider(_blobStore, format)
            );

            if (provider.Filename == null)
                return "Attachment not found!";

            if (provider.FormData["custom-data"] != null)
            {
                _customData = JsonConvert.DeserializeObject<DocumentCustomData>(provider.FormData["custom-data"]);
            }

            _fileName = provider.Filename;
            _blobId = provider.BlobId;
            return null;
        }
        /// <summary>
        /// Upload a file sent in an http request
        /// </summary>
        /// <param name="httpContent">request's content</param>
        /// <returns>Error message or null</returns>
        private async Task<String> UploadFromHttpContent(HttpContent httpContent)
        {
            if (httpContent == null || !httpContent.IsMimeMultipartContent())
                return "Attachment not found!";

            var provider = await httpContent.ReadAsMultipartAsync(
                new FileStoreMultipartStreamProvider(_blobStore, _configService)
            );

            if (provider.Filename == null)
                return "Attachment not found!";

            if (provider.IsInvalidFile)
                return string.Format("Unsupported file {0}", provider.Filename);

            if (provider.FormData["custom-data"] != null)
            {
                _customData = JsonConvert.DeserializeObject<DocumentCustomData>(provider.FormData["custom-data"]);
            }

            _fileName = provider.Filename;
            _blobId = provider.BlobId;
            return null;
        }
        /// <summary>
        ///     Asynchronously deserializes 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 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>
        /// <param name="cancellationToken">The token to cancel the operation.</param>
        public override async Task<object> ReadFromStreamAsync(Type type,
                                                               Stream readStream,
                                                               HttpContent content,
                                                               IFormatterLogger formatterLogger,
                                                               CancellationToken cancellationToken)
        {
            if (!content.IsMimeMultipartContent())
            {
                throw new FormatException("Only multipart/form-data supported");
            }
            var allProps = type.GetProperties().ToDictionary(x => x.Name, StringComparer.InvariantCultureIgnoreCase);
            var instance = Activator.CreateInstance(type);
            var mmsp = await content.ReadAsMultipartAsync();
            foreach (var httpContent in mmsp.Contents)
            {
                var pName = StrHelper.UnquoteToken(httpContent.Headers.ContentDisposition.Name);
                PropertyInfo pi;
                if (!allProps.TryGetValue(pName, out pi))
                {
                    continue;
                }

                object value;
                if (httpContent.Headers.ContentType == null)
                {
                    var converter = TypeDescriptor.GetConverter(pi.PropertyType);
                    value = converter.ConvertFromString(await httpContent.ReadAsStringAsync());
                }
                else
                {
                    var reader = _mediaTypeFormatterCollection.FindReader(pi.PropertyType, httpContent.Headers.ContentType);
                    if (reader == null)
                    {
                        throw new InvalidOperationException(
                                $"Could not found reader for type {pi.PropertyType} with ContentTye {httpContent.Headers.ContentType}");
                    }
                    value = await reader.ReadFromStreamAsync(pi.PropertyType,
                                                             await httpContent.ReadAsStreamAsync(),
                                                             httpContent,
                                                             formatterLogger,
                                                             cancellationToken);
                }
                _propertyHelper.Set(pi, instance, value);
            }
            return instance;
        }
        /// <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));
        }