本文整理汇总了C#中System.Net.Http.HttpContent类的典型用法代码示例。如果您正苦于以下问题:C# HttpContent类的具体用法?C# HttpContent怎么用?C# HttpContent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpContent类属于System.Net.Http命名空间,在下文中一共展示了HttpContent类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: ReadContentAsync
private static string ReadContentAsync(HttpContent content)
{
Task task = content.LoadIntoBufferAsync();
task.Wait(TimeoutConstant.DefaultTimeout);
Assert.Equal(TaskStatus.RanToCompletion, task.Status);
return content.ReadAsStringAsync().Result;
}
开发者ID:KevMoore,项目名称:aspnetwebstack,代码行数:7,代码来源:HttpMessageContentTests.cs
示例2: GetMetadata
/// <summary>
/// Generates a web request to return the user-defined metadata for this container.
/// </summary>
/// <param name="uri">The absolute URI to the container.</param>
/// <param name="timeout">The server timeout interval.</param>
/// <param name="accessCondition">The access condition to apply to the request.</param>
/// <returns>A web request to use to perform the operation.</returns>
public static HttpRequestMessage GetMetadata(Uri uri, int? timeout, AccessCondition accessCondition, HttpContent content, OperationContext operationContext)
{
UriQueryBuilder containerBuilder = GetContainerUriQueryBuilder();
HttpRequestMessage request = HttpRequestMessageFactory.GetMetadata(uri, timeout, containerBuilder, content, operationContext);
request.ApplyAccessCondition(accessCondition);
return request;
}
开发者ID:huoxudong125,项目名称:azure-sdk-for-net,代码行数:14,代码来源:ContainerHttpRequestMessageFactory.cs
示例3: WriteToStreamAsync
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
var writer = new StreamWriter(writeStream);
JSON.Serialize(value, writer, _options);
writer.Flush();
return Task.FromResult(writeStream);
}
开发者ID:alexvance89,项目名称:tinder-api,代码行数:7,代码来源:JilFormatter.cs
示例4: WriteToStreamAsync
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
return Task.Factory.StartNew(() =>
{
XmlWriter writer = new XmlTextWriter(writeStream, new UTF8Encoding(false));
bool summary = requestMessage.RequestSummary();
if (type == typeof(OperationOutcome))
{
Resource resource = (Resource)value;
FhirSerializer.SerializeResource(resource, writer, summary);
}
else if (type.IsAssignableFrom(typeof(Resource)))
{
Resource resource = (Resource)value;
FhirSerializer.SerializeResource(resource, writer, summary);
content.Headers.ContentLocation = resource.ExtractKey().ToUri();
}
else if (type == typeof(FhirResponse))
{
FhirResponse response = (value as FhirResponse);
if (response.HasBody)
FhirSerializer.SerializeResource(response.Resource, writer, summary);
}
writer.Flush();
});
}
开发者ID:Condeti,项目名称:spark,代码行数:30,代码来源:XmlFhirFormatter.cs
示例5: BuildBase64Signature
public static string BuildBase64Signature(
string apiKey,
string appId,
Uri rawUri,
HttpMethod httpMethod,
HttpContent content,
string nonce,
string requestTimeStamp
)
{
var requestUri = HttpUtility.UrlEncode(rawUri.AbsoluteUri.ToLower());
var requestHttpMethod = httpMethod.Method;
// Get the content string out of the content.
string requestContentBase64String = ComputeBase64RequestContent(content);
// Rebuild the signature raw data.
var signatureRawData =
$"{appId}{requestHttpMethod}{requestUri}{requestTimeStamp}{nonce}{requestContentBase64String}";
// Get the api key bytes.
var secretKeyBytes = Convert.FromBase64String(apiKey);
// Get the signature.
var signature = Encoding.UTF8.GetBytes(signatureRawData);
// Create HMAC SHA class with key data.
using (var hmac = new HMACSHA256(secretKeyBytes))
{
return Convert.ToBase64String(hmac.ComputeHash(signature));
}
}
开发者ID:SamStrong,项目名称:WebAPI.HMAC,代码行数:32,代码来源:HMACHelper.cs
示例6: CompressedContent
public CompressedContent(HttpContent content, string encodingType)
{
if (content == null)
{
throw new ArgumentNullException("content");
}
if (encodingType == null)
{
throw new ArgumentNullException("encodingType");
}
originalContent = content;
this.encodingType = encodingType.ToLowerInvariant();
if (this.encodingType != "gzip" && this.encodingType != "deflate")
{
throw new InvalidOperationException(string.Format("Encoding '{0}' is not supported. Only supports gzip or deflate encoding.", this.encodingType));
}
// copy the headers from the original content
foreach (KeyValuePair<string, IEnumerable<string>> header in originalContent.Headers)
{
Headers.TryAddWithoutValidation(header.Key, header.Value);
}
Headers.ContentEncoding.Add(encodingType);
}
开发者ID:heinnge,项目名称:ravendb,代码行数:28,代码来源:CompressedContent.cs
示例7: WriteToStreamAsync
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
return Task.Factory.StartNew(() =>
{
XmlWriter writer = new XmlTextWriter(writeStream, Encoding.UTF8);
// todo: klopt het dat Bundle wel en <?xml ...> header heeft een Resource niet?
// follow up: is now ticket in FhirApi. Check later.
if (type == typeof(OperationOutcome))
{
Resource resource = (Resource)value;
FhirSerializer.SerializeResource(resource, writer);
}
else if (type == typeof(ResourceEntry))
{
ResourceEntry entry = (ResourceEntry)value;
FhirSerializer.SerializeResource(entry.Resource, writer);
content.Headers.SetFhirTags(entry.Tags);
}
else if (type == typeof(Bundle))
{
FhirSerializer.SerializeBundle((Bundle)value, writer);
}
else if (type == typeof(TagList))
{
FhirSerializer.SerializeTagList((TagList)value, writer);
}
writer.Flush();
});
}
开发者ID:TonyAbell,项目名称:spark,代码行数:33,代码来源:XmlFhirFormatter.cs
示例8: WriteToStream
public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
{
try
{
var buffer = new byte[65536];
using (var video = new MemoryStream(this.videoData))
{
var length = (int)video.Length;
var bytesRead = 1;
while (length > 0 && bytesRead > 0)
{
bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
await outputStream.WriteAsync(buffer, 0, bytesRead);
length -= bytesRead;
}
}
}
catch (Exception ex)
{
return;
}
finally
{
outputStream.Close();
}
}
开发者ID:KitKare,项目名称:KitKareService,代码行数:28,代码来源:VideoStream.cs
示例9: ReadFromStreamAsync
//public JsonFormatter()
//{
// SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
// SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
//}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var task = new TaskCompletionSource<object>();
using (var ms = new MemoryStream())
{
readStream.CopyTo(ms);
//ms.Seek(0, SeekOrigin.Begin);
//var result = JsonSchemaValidator.Instance().Validate(ms, type);
//if (!string.IsNullOrWhiteSpace(result))
// task.SetResult(result);
//else
{
ms.Seek(0, SeekOrigin.Begin);
using (var reader = new JsonTextReader(new StreamReader(ms)))
{
var serializer = new JsonSerializer();
task.SetResult(serializer.Deserialize(reader, type));
}
}
}
return task.Task;
}
开发者ID:shanmukhig,项目名称:tms,代码行数:30,代码来源:JsonFormatter.cs
示例10: WriteToStream
public void WriteToStream(Type type, object value, Stream stream, HttpContent content)
{
Author author = (Author)value;
Image image = Image.FromFile(@"D:\dev\CodicePlastico\WebApiBook\HelloWebApi\HelloWebApi\Content\Photos\" + author.Name + ".png");
image.Save(stream, ImageFormat.Png);
image.Dispose();
}
开发者ID:emadb,项目名称:WebApiSamples,代码行数:7,代码来源:ImageFormatter.cs
示例11: ReadFromStreamAsync
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
return Task.Factory.StartNew(() =>
{
return (object)null;
});
}
开发者ID:Condeti,项目名称:spark,代码行数:7,代码来源:ResourceJsonFormatter.cs
示例12: 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
示例13: ReadFromStreamAsync
public override async Task<object> ReadFromStreamAsync(Type type, Stream stream,
HttpContent httpContent,
IFormatterLogger iFormatterLogger)
{
MultipartStreamProvider parts = await httpContent.ReadAsMultipartAsync();
IEnumerable<HttpContent> contents = parts.Contents;
HttpContent content = contents.FirstOrDefault();
foreach (HttpContent c in contents ) {
if (SupportedMediaTypes.Contains(c.Headers.ContentType)) {
content = c;
break;
}
}
using (var msgStream = await content.ReadAsStreamAsync())
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(TenMsg));
TenMsg msg = (TenMsg)js.ReadObject(msgStream);
Debug.WriteLine("msgString: " + msgStream.ToString());
int sender = msg.Sender;
int receiver = msg.Receiver;
byte phoneType = msg.PhoneType;
bool isLocked = msg.IsLocked;
DateTime msgTime = msg.MsgTime;
string msgContent = msg.MsgContent;
Debug.WriteLine("Msg Content: " + msg.MsgContent);
return new TenMsg(sender, receiver, phoneType, isLocked, msgTime, msgContent);
}
}
开发者ID:LiMao-Tech,项目名称:TenBackend,代码行数:32,代码来源:TenMsgMediaFormatter.cs
示例14: ReadFromStreamAsync
public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
MultipartMemoryStreamProvider multipartMemoryStreamProvider = await content.ReadAsMultipartAsync();
Collection<HttpContent> contents = multipartMemoryStreamProvider.Contents;
ImageSet imageSet = await contents.FirstOrDefault<HttpContent>((HttpContent c) => c.Headers.ContentDisposition.Name.NormalizeName() == "imageset").ReadAsAsync<ImageSet>();
ImageSet images = imageSet;
Collection<HttpContent> httpContents = multipartMemoryStreamProvider.Contents;
List<HttpContent> list = (
from c in httpContents
where c.Headers.ContentDisposition.Name.NormalizeName().Matches("image\\d+")
select c).ToList<HttpContent>();
images.Images = new List<Image>();
foreach (HttpContent httpContent in list)
{
List<Image> images1 = images.Images;
Image image = new Image();
Image image1 = image;
image1.ImageData = await httpContent.ReadAsByteArrayAsync();
image.MimeType = httpContent.Headers.ContentType.MediaType;
image.FileName = httpContent.Headers.ContentDisposition.FileName.NormalizeName();
images1.Add(image);
images1 = null;
image1 = null;
image = null;
}
return images;
}
开发者ID:vmfdesign,项目名称:Portal,代码行数:27,代码来源:ImageSetMediaTypeFormatter.cs
示例15: HttpAbfrage
HttpAbfrage(String Ziel, HttpContent content)
{
//################################################################################################
var httpClient = new HttpClient(); // Neue httpClient instanz
//##################################################################################################
// mit Cockies aber nicht zu ende Programmiert weil wir keine Cockies nutzen
CookieContainer cookie = new CookieContainer(); // Cockie Container Construcktor
HttpClientHandler handler = new HttpClientHandler() // nutze beim zugriff cockies
{
};
HttpClient client = new HttpClient(handler as HttpMessageHandler) // neuer http client
{
BaseAddress = new Uri(GlobalData.Uri2 + Ziel + GlobalData.SessionID) // hier wird auch gleich die Session an das ziel angehangen // url aus uri 2 nutzen test2.php
};
handler.UseCookies = false; // beim zugriff cockies nicht zulassen
handler.UseDefaultCredentials = false;
//#################################################################################################
// Jetzt mit POST
// Schritt 4 Abfrage abschicken und ergebnis entgegennehmen
HttpResponseMessage response = await httpClient.PostAsync(client.BaseAddress, content); // schicke die abfrage an die Url , dann warte bis antwort komplett und speicher erst mal alles
GlobalData.HttpResponse = await response.Content.ReadAsStringAsync();
// MessageDialog msgboxRespons = new MessageDialog(GlobalData.HttpResponse);
// await msgboxRespons.ShowAsync(); // Zeige mir an was angekommen ist
return GlobalData.HttpResponse;
}
开发者ID:RobinBrandt87,项目名称:OSS,代码行数:30,代码来源:Globalfunctions.cs
示例16: AuthRequest
private async Task<JObject> AuthRequest(string path, string method, HttpContent data, RequestingUser u) {
using(HttpClientHandler handler = new HttpClientHandler())
using(HttpClient client = new HttpClient(handler)) {
HttpResponseMessage msg = null;
string str;
if(u != null) {
handler.UseCookies = true;
handler.CookieContainer = new CookieContainer();
u.Cookies.ToList().ForEach(c => handler.CookieContainer.Add(c));
client.DefaultRequestHeaders.Add("x-csrf", u.CsrfToken);
}
else {
handler.UseCookies = false;
}
if(method.ToUpper() == WebRequestMethods.Http.Get.ToUpper()) {
msg = await client.GetAsync(BungieNet.PlatformPath + path);
}
else if(method.ToUpper() == WebRequestMethods.Http.Post.ToUpper()) {
msg = await client.PostAsync(BungieNet.PlatformPath + path, data);
}
str = await msg.Content.ReadAsStringAsync();
return JObject.Parse(str);
}
}
开发者ID:d1enamic,项目名称:BungieNetPlatform-CSharp,代码行数:32,代码来源:Platform.cs
示例17: CreateRequestMessage
/// <summary>
/// Creates the web request.
/// </summary>
/// <param name="uri">The request Uri.</param>
/// <param name="timeout">The timeout.</param>
/// <param name="builder">The builder.</param>
/// <returns>A web request for performing the operation.</returns>
internal static StorageRequestMessage CreateRequestMessage(HttpMethod method, Uri uri, int? timeout, UriQueryBuilder builder, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials)
{
if (builder == null)
{
builder = new UriQueryBuilder();
}
if (timeout.HasValue && timeout.Value > 0)
{
builder.Add("timeout", timeout.ToString());
}
#if WINDOWS_RT && !NETCORE
// Windows Phone does not allow the caller to disable caching, so a random GUID
// is added to every URI to make it look like a different request.
builder.Add("randomguid", Guid.NewGuid().ToString("N"));
#endif
Uri uriRequest = builder.AddToUri(uri);
StorageRequestMessage msg = new StorageRequestMessage(method, uriRequest, canonicalizer, credentials, credentials.AccountName);
msg.Content = content;
return msg;
}
开发者ID:mirobers,项目名称:azure-storage-net,代码行数:32,代码来源:HttpRequestMessageFactory.cs
示例18: VerifyResponse
public static void VerifyResponse(HttpContent responseContent, string expected)
{
string response = responseContent.ReadAsStringAsync().Result;
Regex updatedRegEx = new Regex("<updated>*.*</updated>");
response = updatedRegEx.Replace(response, "<updated>UpdatedTime</updated>");
Assert.Xml.Equal(expected, response);
}
开发者ID:quentez,项目名称:aspnetwebstack,代码行数:7,代码来源:ODataTestUtil.cs
示例19: ReadFromStreamAsync
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
return Task.Factory.StartNew(() =>
{
MemoryStream stream = new MemoryStream();
readStream.CopyTo(stream);
IEnumerable<string> xContentHeader;
var success = content.Headers.TryGetValues("X-Content-Type", out xContentHeader);
if (!success)
{
throw Error.BadRequest("POST to binary must provide a Content-Type header");
}
string contentType = xContentHeader.FirstOrDefault();
Binary binary = new Binary();
binary.Content = stream.ToArray();
binary.ContentType = contentType;
//ResourceEntry entry = ResourceEntry.Create(binary);
//entry.Tags = content.Headers.GetFhirTags();
return (object)binary;
});
}
开发者ID:Condeti,项目名称:spark,代码行数:26,代码来源:BinaryFormatter.cs
示例20: Respond
/// <summary>
/// Sets the response of the current <see cref="T:MockedRequest"/>
/// </summary>
/// <param name="source">The source mocked request</param>
/// <param name="statusCode">The <see cref="T:HttpStatusCode"/> of the response</param>
/// <param name="content">The content of the response</param>
public static void Respond(this MockedRequest source, HttpStatusCode statusCode, HttpContent content)
{
HttpResponseMessage message = new HttpResponseMessage(statusCode);
message.Content = content;
source.Respond(message);
}
开发者ID:EdsonF,项目名称:mockhttp,代码行数:13,代码来源:MockedRequestExtensions.cs
注:本文中的System.Net.Http.HttpContent类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论