当前位置: 首页>>代码示例>>C#>>正文


C# HttpContent.IsMimeMultipartContent方法代码示例

本文整理汇总了C#中System.Net.Http.HttpContent.IsMimeMultipartContent方法的典型用法代码示例。如果您正苦于以下问题:C# HttpContent.IsMimeMultipartContent方法的具体用法?C# HttpContent.IsMimeMultipartContent怎么用?C# HttpContent.IsMimeMultipartContent使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Http.HttpContent的用法示例。


在下文中一共展示了HttpContent.IsMimeMultipartContent方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ReadFromStreamAsync

        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) };
            }
        }
开发者ID:keithb-,项目名称:Valley,代码行数:28,代码来源:GenericMediaTypeFormatter.cs

示例2: ReadFromStreamAsync

        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;
            }
                   
        }
开发者ID:MicrosoftDX,项目名称:AzureLens,代码行数:30,代码来源:ImageMediaModels.cs

示例3: Convert

        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;
        }
开发者ID:RhysC,项目名称:ImageUploader,代码行数:15,代码来源:HttpContentToFormDataConverter.cs

示例4: ReadFromStreamAsync

        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;
        }
开发者ID:saibalghosh,项目名称:Layout3,代码行数:48,代码来源:FileMediaFormatter.cs

示例5: WriteToStreamAsync

        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;
        }
开发者ID:kooldave98,项目名称:Rangr-API,代码行数:17,代码来源:FormMultipartEncodedMediaTypeFormatter.cs

示例6: ReadFromStreamAsync

        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;
        }
开发者ID:RomanAnosov,项目名称:Repo,代码行数:20,代码来源:ImageMultipartMediaFormatter.cs

示例7: ReadFromStreamAsync

        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);
        }
开发者ID:AnastasiyaKislach,项目名称:SalonLesanj,代码行数:20,代码来源:FileModelFormatter.cs

示例8: ReadFromStreamAsync

        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;
            });
        }
开发者ID:vebin,项目名称:IFramework,代码行数:41,代码来源:MultipartMediaTypeFormatter.cs

示例9: UploadAnyFileAsync

        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;
        }
开发者ID:LeagueOfDevelopers,项目名称:LodCore,代码行数:22,代码来源:FileManager.cs

示例10: ReadFromStreamAsync

        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;

        }
开发者ID:Budzyn,项目名称:hunter,代码行数:24,代码来源:UploadFormater.cs

示例11: AddFormatFromHttpContent

        /// <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;
        }
开发者ID:ProximoSrl,项目名称:Jarvis.DocumentStore,代码行数:26,代码来源:DocumentsController.cs

示例12: UploadFromHttpContent

        /// <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;
        }
开发者ID:ProximoSrl,项目名称:Jarvis.DocumentStore,代码行数:29,代码来源:DocumentsController.cs

示例13: FindMultipartRelatedParameter

        /// <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));
        }
开发者ID:RossMerr,项目名称:azure-sdk-for-net,代码行数:22,代码来源:MultipartRelatedStreamProvider.cs

示例14: ReadFromStreamAsync

        /// <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;
        }
开发者ID:riberk,项目名称:Rib.Common,代码行数:57,代码来源:MultipartMediaTypeFormatter.cs


注:本文中的System.Net.Http.HttpContent.IsMimeMultipartContent方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。