本文整理汇总了C#中System.Net.Http.Headers.HttpContentHeaders类的典型用法代码示例。如果您正苦于以下问题:C# HttpContentHeaders类的具体用法?C# HttpContentHeaders怎么用?C# HttpContentHeaders使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpContentHeaders类属于System.Net.Http.Headers命名空间,在下文中一共展示了HttpContentHeaders类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: SetDefaultContentHeaders
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
base.SetDefaultContentHeaders(type, headers, mediaType);
headers.ContentType = new MediaTypeHeaderValue(ApplicationJsonMediaType);
this.SerializerSettings.Formatting = Formatting.None;
this.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
开发者ID:spptest,项目名称:Telerik,代码行数:7,代码来源:BrowserJsonFormatter.cs
示例2: PopulateHeaders
public static void PopulateHeaders(this HttpPacket packet, HttpContentHeaders contentHeaders, HttpHeaders generalHeaders)
{
if (packet == null) throw new ArgumentNullException("packet");
string hdrKey;
foreach (var hdr in packet.Headers)
{
if (hdr.Key == null) continue;
hdrKey = hdr.Key.Trim().ToUpperInvariant();
if (hdrKey == "CONTENT-LENGTH") continue; //Content Length is automaitically calculated
if (Array.IndexOf<String>(contentOnlyHeaders, hdrKey) >= 0)
{
//TODO: Confirm if HttpResponseMessage/HttpRequestMessage will break headers into "," commas whereas in actuality header in Packet is an entire header
contentHeaders.Add(hdr.Key.Trim(), hdr.Value);
}
else
{
generalHeaders.Add(hdr.Key.Trim(), hdr.Value);
}
//TODO: Check if a string can be parsed properly into the typed header
//Test adding multiple headers of the same name will do. // Look up the Add overload that takes an ienumerable<string> to figure out its purpose.
}
}
开发者ID:BrisWhite,项目名称:RestBus,代码行数:28,代码来源:HttpHelpers.cs
示例3: GetStream
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
if (parent == null)
{
throw Error.ArgumentNull("parent");
}
if (headers == null)
{
throw Error.ArgumentNull("headers");
}
string localFilePath;
try
{
string filename = this.GetLocalFileName(headers);
localFilePath = Path.Combine(this._rootPath, Path.GetFileName(filename));
}
catch (Exception e)
{
throw Error.InvalidOperation(e, Resources.MultipartStreamProviderInvalidLocalFileName);
}
// Add local file name
MultipartFileData fileData = new MultipartFileData(headers, localFilePath);
this._fileData.Add(fileData);
return File.Create(localFilePath, this._bufferSize, FileOptions.Asynchronous);
}
开发者ID:RossMerr,项目名称:azure-sdk-for-net,代码行数:29,代码来源:MultipartFileStreamProvider.cs
示例4: ContentLength_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison
public void ContentLength_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison()
{
_headers = new HttpContentHeaders(new ComputeLengthHttpContent(() => 15));
// Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison.
Assert.Throws<FormatException>(() => { _headers.Add("CoNtEnT-LeNgTh", "this is invalid"); });
}
开发者ID:dotnet,项目名称:corefx,代码行数:7,代码来源:HttpContentHeadersTest.cs
示例5: IsFileContent
public static bool IsFileContent(HttpContent parent, HttpContentHeaders headers)
{
if (parent == null)
{
throw new ArgumentNullException("parent");
}
if (headers == null)
{
throw new ArgumentNullException("headers");
}
// For form data, Content-Disposition header is a requirement.
ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
if (contentDisposition == null)
{
// If no Content-Disposition header was present.
throw new InvalidOperationException("No Content-Disposition header found");
}
// The file name's existence indicates it is a file data.
if (!string.IsNullOrEmpty(contentDisposition.FileName))
{
return true;
}
return false;
}
开发者ID:pekkah,项目名称:Tanka.FileSystem.WebApi,代码行数:28,代码来源:FlowTemporaryFileProvider.cs
示例6: CopyHeaders
private static void CopyHeaders(HttpContentHeaders fromHeaders,
HttpContentHeaders toHeaders)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in fromHeaders) {
toHeaders.Add(header.Key, header.Value);
}
}
开发者ID:cairabbit,项目名称:daf,代码行数:7,代码来源:HeadMessageHandler.cs
示例7: OnWriteToStreamAsync
protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream,
HttpContentHeaders contentHeaders,
FormatterContext formatterContext,
TransportContext transportContext)
{
string callback;
if (IsJsonpRequest(formatterContext.Response.RequestMessage, out callback))
{
return Task.Factory.StartNew(() =>
{
var writer = new StreamWriter(stream);
writer.Write(callback + "(");
writer.Flush();
base.OnWriteToStreamAsync(type, value, stream, contentHeaders,
formatterContext, transportContext).Wait();
writer.Write(")");
writer.Flush();
});
}
else
{
return base.OnWriteToStreamAsync(type, value, stream, contentHeaders, formatterContext, transportContext);
}
}
开发者ID:mikaelo,项目名称:SecureWebAPI,代码行数:27,代码来源:JsonPFormatter.cs
示例8: AddRange
public void AddRange(HttpContentHeaders headers)
{
foreach (var header in headers)
{
this._headers.Add(header.Key, header.Value);
}
}
开发者ID:jasonzhuyx,项目名称:openstack-sdk-dotnet,代码行数:7,代码来源:HttpHeadersAbstraction.cs
示例9: OnWriteToStreamAsync
protected override System.Threading.Tasks.Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
{
return new TaskFactory().StartNew(() =>
{
new StreamWriter(stream).Write((string)value);
});
}
开发者ID:filipw,项目名称:RestAgent,代码行数:7,代码来源:PlainTextFormatter.cs
示例10: OnReadFromStreamAsync
protected override System.Threading.Tasks.Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
{
return new TaskFactory<object>().StartNew(() =>
{
return new StreamReader(stream).ReadToEnd();
});
}
开发者ID:filipw,项目名称:RestAgent,代码行数:7,代码来源:PlainTextFormatter.cs
示例11: GetStream
/// <summary>
/// This body part stream provider examines the headers provided by the MIME multipart parser
/// and decides whether it should return a file stream or a memory stream for the body part to be
/// written to.
/// </summary>
/// <param name="parent">The parent MIME multipart HttpContent instance.</param>
/// <param name="headers">Header fields describing the body part</param>
/// <returns>The <see cref="Stream"/> instance where the message body part is written to.</returns>
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
if (parent == null)
{
throw Error.ArgumentNull("parent");
}
if (headers == null)
{
throw Error.ArgumentNull("headers");
}
// For form data, Content-Disposition header is a requirement
ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
if (contentDisposition != null)
{
// If we have a file name then write contents out to temporary file. Otherwise just write to MemoryStream
if (!String.IsNullOrEmpty(contentDisposition.FileName))
{
// We won't post process files as form data
_isFormData.Add(false);
return base.GetStream(parent, headers);
}
// We will post process this as form data
_isFormData.Add(true);
// If no filename parameter was found in the Content-Disposition header then return a memory stream.
return new MemoryStream();
}
// If no Content-Disposition header was present.
throw Error.InvalidOperation(Properties.Resources.MultipartFormDataStreamProviderNoContentDisposition, "Content-Disposition");
}
开发者ID:tlycken,项目名称:aspnetwebstack,代码行数:43,代码来源:MultipartFormDataStreamProvider.cs
示例12: SetContentType
public virtual void SetContentType(Type type, HttpContentHeaders headers, string mediaType)
{
if (this.SupportedMediaTypes == null) {
throw new InvalidOperationException(string.Format("{0} does not set support media types", base.GetType()));
}
headers.ContentType = this.SupportedMediaTypes.Contains(mediaType) ? mediaType : this.SupportedMediaTypes.First();
}
开发者ID:beginor,项目名称:System_Net_Http,代码行数:7,代码来源:MediaTypeFormatter.cs
示例13: ContentLength_UseAddMethod_AddedValueCanBeRetrievedUsingProperty
public void ContentLength_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
_headers = new HttpContentHeaders(() => { Assert.True(false, "Delegate called."); return 0; });
_headers.TryAddWithoutValidation(HttpKnownHeaderNames.ContentLength, " 68 \r\n ");
Assert.Equal(68, _headers.ContentLength);
}
开发者ID:johnhhm,项目名称:corefx,代码行数:7,代码来源:HttpContentHeadersTest.cs
示例14: GetStream
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
Stream stream = null;
ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
if (contentDisposition != null)
{
if (!String.IsNullOrWhiteSpace(contentDisposition.FileName))
{
string connectionString = ConfigurationManager.AppSettings["azureConnectionString"];
var containerName = ConfigurationManager.AppSettings["container"];
if (contentDisposition.Name.Contains("avatar"))
containerName = "avatar";
if (contentDisposition.Name.Contains("headerImage"))
containerName = "header";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);
CloudBlockBlob blob = blobContainer.GetBlockBlobReference(Guid.NewGuid().ToString() + ".jpg");
blob.Metadata.Add("source", ConfigurationManager.AppSettings["source"]);
if (_breweryDto != null) blob.Metadata.Add("breweryId", _breweryDto.Id.ToString());
if(_userDto != null) blob.Metadata.Add("username", _userDto.Username);
stream = blob.OpenWrite();
headers.ContentDisposition.FileName = blob.Name;
}
}
return stream;
}
开发者ID:johnfredrik,项目名称:MicrobrewitApi,代码行数:29,代码来源:BlobStorageMultipartStreamProvider.cs
示例15: GetStream
/// <summary>
/// <para>This method assumes that all form segments come before the actual file data.</para>
/// <para>Otherwise, GetLocalFileName will fail.</para>
/// </summary>
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
if (headers.ContentDisposition.FileName == null)
{
return base.GetStream(parent, headers);
}
string flowFileName = null;
try
{
flowFileName = GetLocalFileName(headers);
}
catch (Exception ex)
{
throw new Exception("Flow chunk information was not properly transmitted before the chunk payload.", ex);
}
FileStream flowFileStream;
var path = Path.Combine(RootPath, flowFileName);
flowFileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
flowFileStream.SetLength(MetaData.FlowTotalSize);
flowFileStream.Seek(MetaData.FileOffset, 0);
return flowFileStream;
}
开发者ID:ShyAlon,项目名称:DeepDev,代码行数:35,代码来源:FlowMultipartFormDataStreamProvider.cs
示例16: GetLocalFileName
protected virtual string GetLocalFileName(HttpContentHeaders headers)
{
if (headers == null)
{
throw new ArgumentNullException("headers");
}
string str = null;
try
{
ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
if (contentDisposition != null)
{
str = ExtractLocalFileName(contentDisposition);
}
}
catch (Exception)
{
}
if (str == null)
{
str = string.Format(CultureInfo.InvariantCulture, "BodyPart_{0}", new object[] { Guid.NewGuid() });
}
return str;
}
开发者ID:Ekus,项目名称:MyPictures,代码行数:28,代码来源:MultipartMemoryStreamProvider.cs
示例17: ReadFromStream
public override object ReadFromStream(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
{
BufferedMediaTypeFormatter innerFormatter = InnerBufferedFormatter;
MediaTypeHeaderValue contentType = contentHeaders == null ? null : contentHeaders.ContentType;
object value = null;
_innerTracer.TraceWriter.TraceBeginEnd(
_innerTracer.Request,
TraceCategories.FormattingCategory,
TraceLevel.Info,
_innerTracer.InnerFormatter.GetType().Name,
OnReadFromStreamMethodName,
beginTrace: (tr) =>
{
tr.Message = Error.Format(
SRResources.TraceReadFromStreamMessage,
type.Name,
contentType == null ? SRResources.TraceNoneObjectMessage : contentType.ToString());
},
execute: () =>
{
value = innerFormatter.ReadFromStream(type, stream, contentHeaders, formatterLogger);
},
endTrace: (tr) =>
{
tr.Message = Error.Format(
SRResources.TraceReadFromStreamValueMessage,
FormattingUtilities.ValueToString(value, CultureInfo.CurrentCulture));
},
errorTrace: null);
return value;
}
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:33,代码来源:BufferedMediaTypeFormatterTracer.cs
示例18: GetStream
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
if (parent == null) throw new ArgumentNullException(nameof(parent));
if (headers == null) throw new ArgumentNullException(nameof(headers));
if (!_supportedMimeTypes.Contains(headers.ContentType.ToString().ToLower()))
{
throw new NotSupportedException("Only jpeg and png are supported");
}
// Generate a new filename for every new blob
var fileName = Guid.NewGuid().ToString();
CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(fileName);
if (headers.ContentType != null)
{
// Set appropriate content type for your uploaded file
blob.Properties.ContentType = headers.ContentType.MediaType;
}
this.FileData.Add(new MultipartFileData(headers, blob.Name));
return blob.OpenWrite();
}
开发者ID:ppolyzos,项目名称:DemoAzureStorage,代码行数:25,代码来源:AzureStorageMultipartFormDataStreamProvider.cs
示例19: ReadFromStreamAsync
public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
{
Task<IEnumerable<HttpContent>> readAsMultipartAsync = _httpRequestMessage.Content.ReadAsMultipartAsync();
IEnumerable<HttpContent> httpContents = readAsMultipartAsync.Result;
HttpContent content = httpContents.First(x => SupportedMediaTypes.Contains(x.Headers.ContentType));
string fileName = content.Headers.ContentDisposition.FileName;
string mediaType = content.Headers.ContentType.MediaType;
Task<Stream> readAsStreamAsync = content.ReadAsStreamAsync();
byte[] readFully = readAsStreamAsync.Result.ReadFully();
var taskCompletionSource = new TaskCompletionSource<object>();
taskCompletionSource.SetResult(new ImageMedia(fileName, mediaType, readFully));
return taskCompletionSource.Task;
// var taskCompletionSource = new TaskCompletionSource<object>();
// try
// {
// var memoryStream = new MemoryStream();
// stream.CopyTo(memoryStream);
// var s = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
// taskCompletionSource.SetResult(s);
// }
// catch (Exception e)
// {
// taskCompletionSource.SetException(e);
// }
// return taskCompletionSource.Task;
}
开发者ID:ahmetoz,项目名称:Photopia,代码行数:35,代码来源:ImageMediaFormatter.cs
示例20: ReadFromStreamAsync
public override Task<object> ReadFromStreamAsync(Type type, HttpContentHeaders headers, Stream stream)
{
var tcs = new TaskCompletionSource<object>();
try {
var serializer = GetSerializerForType(type);
if (serializer == null) {
tcs.TrySetException(new InvalidOperationException(string.Format("Can not create serializer for {0}", type)));
}
else {
Task<object>.Factory.StartNew(() => serializer.Deserialize(stream))
.ContinueWith(t => {
if (t.IsFaulted) {
tcs.TrySetException(t.Exception.GetBaseException());
}
else if (t.IsCanceled) {
tcs.TrySetCanceled();
}
else {
tcs.TrySetResult(t.Result);
}
}, TaskContinuationOptions.ExecuteSynchronously);
}
}
catch (Exception ex) {
tcs.TrySetException(ex);
}
return tcs.Task;
}
开发者ID:beginor,项目名称:System_Net_Http,代码行数:28,代码来源:XmlMediaTypeFormatter.cs
注:本文中的System.Net.Http.Headers.HttpContentHeaders类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论