本文整理汇总了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) };
}
}
示例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;
}
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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);
}
示例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;
});
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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));
}
示例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;
}