本文整理汇总了C#中System.Net.Http.StreamContent.ReadAsAsync方法的典型用法代码示例。如果您正苦于以下问题:C# StreamContent.ReadAsAsync方法的具体用法?C# StreamContent.ReadAsAsync怎么用?C# StreamContent.ReadAsAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.StreamContent
的用法示例。
在下文中一共展示了StreamContent.ReadAsAsync方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
private static void Main(string[] args)
{
const int TotalRun = 10*1000;
var customerController = new CustomerController();
var orderController = new OrderController();
var customer = customerController.Get(1);
var orders = new List<Order>();
foreach (var orderId in customer.OrderIds)
{
orders.Add(orderController.Get(1, orderId));
}
var fullCustomer = new FullCustomer(customer)
{
Orders = orders
};
var s = JsonConvert.SerializeObject(fullCustomer);
var bytes = Encoding.UTF8.GetBytes(s);
var stream = new MemoryStream(bytes);
var content = new StreamContent(stream);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var stopwatch = Stopwatch.StartNew();
for (int i = 1; i < TotalRun+1; i++)
{
var a = content.ReadAsAsync<FullCustomer>().Result;
if(i % 100 == 0)
Console.Write("\r" + i);
}
Console.WriteLine();
Console.WriteLine(stopwatch.Elapsed);
stopwatch.Restart();
for (int i = 1; i < TotalRun+1; i++)
{
var sa = content.ReadAsStringAsync().Result;
var a = JsonConvert.DeserializeObject<FullCustomer>(sa);
if (i % 100 == 0)
Console.Write("\r" + i);
}
Console.WriteLine();
Console.WriteLine(stopwatch.Elapsed);
Console.Read();
}
示例2: BindFromBody
private async Task BindFromBody(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
var bodyBinding = _descriptor.BindWithAttribute(new FromBodyAttribute());
var memoryStream = new MemoryStream();
await actionContext.Request.Content.CopyToAsync(memoryStream);
memoryStream.Position = 0;
var content = new StreamContent(memoryStream);
actionContext.Request.Content.Headers.AsEnumerable().ToList().ForEach(x => content.Headers.TryAddWithoutValidation(x.Key, x.Value));
actionContext.Request.Content = new StreamContent(memoryStream);
await bodyBinding.ExecuteBindingAsync(metadataProvider, actionContext, cancellationToken);
var query = GetValue(actionContext) as IClientQuery;
if (query == null)
{
SetValue(actionContext, null);
return;
}
var clientFilterable = query as IClientFilterable;
var clientSortable = query as IClientSortable;
var clientPageable = query as IClientPageable;
memoryStream.Position = 0;
var apiQuery = await content.ReadAsAsync(typeof(ApiQuery), actionContext.ControllerContext.Configuration.Formatters, cancellationToken) as ApiQuery;
if (apiQuery == null)
{
return;
}
if (clientFilterable != null && apiQuery.Filter != null && !(apiQuery.Filter is AlwaysTrueFilter))
{
clientFilterable.ClientFilter = apiQuery.Filter;
}
if (clientSortable != null && apiQuery.Sort != null && !(apiQuery.Sort is RandomSort))
{
clientSortable.ClientSort = apiQuery.Sort;
}
if (clientPageable != null && (apiQuery.PageSize != null && apiQuery.PageNumber != null))
{
clientPageable.ClientPage = new ClientPage
{
PageNumber = apiQuery.PageNumber,
PageSize = apiQuery.PageSize
};
}
SetValue(actionContext, query);
}
示例3: ConvertResponse_Returns_Error_Response_When_Formatter_Write_Throws_Immediately
public void ConvertResponse_Returns_Error_Response_When_Formatter_Write_Throws_Immediately()
{
// Arrange
Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };
formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),
It.IsAny<object>(),
It.IsAny<Stream>(),
It.IsAny<HttpContent>(),
It.IsAny<TransportContext>())).Throws(new NotSupportedException("Expected error"));
MemoryStream memoryStream = new MemoryStream();
Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);
HttpResponseBase responseBase = contextMock.Object.Response;
HttpRequestMessage request = new HttpRequestMessage();
request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy<bool>(() => true));
HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };
response.Content = new ObjectContent<string>("hello", formatterMock.Object);
// Act
Task task = HttpControllerHandler.ConvertResponse(contextMock.Object, response, request);
task.Wait();
// Assert preparation -- deserialize the HttpError response
HttpError httpError = null;
memoryStream.Seek(0L, SeekOrigin.Begin);
using (StreamContent content = new StreamContent(memoryStream))
{
content.Headers.ContentType = JsonMediaTypeFormatter.DefaultMediaType;
httpError = content.ReadAsAsync<HttpError>().Result;
}
// Assert
Assert.Equal<int>((int)HttpStatusCode.InternalServerError, responseBase.StatusCode);
Assert.True(responseBase.Headers["Content-Type"].StartsWith(JsonMediaTypeFormatter.DefaultMediaType.MediaType));
Assert.Equal("An error has occurred.", httpError["Message"]);
Assert.Equal("The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.", httpError["ExceptionMessage"]);
Assert.Equal(typeof(InvalidOperationException).FullName, httpError["ExceptionType"]);
Assert.True(httpError.ContainsKey("StackTrace"));
JObject jObject = httpError["InnerException"] as JObject;
Assert.NotNull(jObject);
Assert.Equal(typeof(NotSupportedException).FullName, jObject["ClassName"].ToString());
Assert.Equal("Expected error", jObject["Message"].ToString());
Assert.Contains("System.Net.Http.HttpContent.CopyToAsync", jObject["StackTraceString"].ToString());
}
示例4: ConvertResponse_Returns_Error_Response_When_Formatter_Write_Task_Faults
public void ConvertResponse_Returns_Error_Response_When_Formatter_Write_Task_Faults()
{
// Arrange
Mock<JsonMediaTypeFormatter> formatterMock = new Mock<JsonMediaTypeFormatter>() { CallBase = true };
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
try
{
// to capture stack trace inside this method
throw new NotSupportedException("Expected error");
}
catch (Exception ex)
{
tcs.SetException(ex);
}
formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny<Type>(),
It.IsAny<object>(),
It.IsAny<Stream>(),
It.IsAny<HttpContent>(),
It.IsAny<TransportContext>())).Returns(tcs.Task);
MemoryStream memoryStream = new MemoryStream();
Mock<HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream);
HttpResponseBase responseBase = contextMock.Object.Response;
HttpRequestMessage request = new HttpRequestMessage();
request.SetIsLocal(new Lazy<bool>(() => true));
HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request };
response.Content = new ObjectContent<string>("hello", formatterMock.Object);
// Act
Task task = HttpControllerHandler.ConvertResponse(contextMock.Object, response, request);
task.Wait();
// Assert preparation -- deserialize the HttpError response
HttpError httpError = null;
memoryStream.Seek(0L, SeekOrigin.Begin);
using (StreamContent content = new StreamContent(memoryStream))
{
content.Headers.ContentType = JsonMediaTypeFormatter.DefaultMediaType;
httpError = content.ReadAsAsync<HttpError>().Result;
}
// Assert
Assert.Equal<int>((int)HttpStatusCode.InternalServerError, responseBase.StatusCode);
Assert.True(responseBase.Headers["Content-Type"].StartsWith(JsonMediaTypeFormatter.DefaultMediaType.MediaType));
Assert.Equal("An error has occurred.", httpError["Message"]);
Assert.Equal("The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.", httpError["ExceptionMessage"]);
Assert.Equal(typeof(InvalidOperationException).FullName, httpError["ExceptionType"]);
Assert.True(httpError.ContainsKey("StackTrace"));
HttpError innerError = (httpError["InnerException"] as JObject).ToObject<HttpError>();
Assert.NotNull(innerError);
Assert.Equal(typeof(NotSupportedException).FullName, innerError["ExceptionType"].ToString());
Assert.Equal("Expected error", innerError["ExceptionMessage"]);
Assert.Contains(MethodInfo.GetCurrentMethod().Name, innerError["StackTrace"].ToString());
}
示例5: ObjectContentShouldReturnAnObject
public void ObjectContentShouldReturnAnObject()
{
//Arrange
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
sw.Write("Hi you");
sw.Flush();
var streamcontent = new StreamContent(ms);
streamcontent.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
//Act
var value = streamcontent.ReadAsAsync<object>(new List<MediaTypeFormatter>() {new PlainTextFormatter()}).Result;
//Assert
Assert.IsInstanceOfType(value,typeof(string));
}
示例6: ReadAsAsyncOfT_formatters_formatterLogger_cancellationToken_PassesCancellationTokenFurther
public void ReadAsAsyncOfT_formatters_formatterLogger_cancellationToken_PassesCancellationTokenFurther()
{
// Arrange
Stream stream = new MemoryStream();
HttpContent content = new StreamContent(stream);
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/test");
CancellationToken token = new CancellationToken();
IFormatterLogger formatterLogger = new Mock<IFormatterLogger>().Object;
Mock<MediaTypeFormatter> formatter = new Mock<MediaTypeFormatter>(MockBehavior.Strict);
formatter.Object.SupportedMediaTypes.Add(content.Headers.ContentType);
formatter.Setup(f => f.CanReadType(typeof(int))).Returns(true);
formatter
.Setup(f => f.ReadFromStreamAsync(typeof(int), It.IsAny<Stream>(), content, formatterLogger, token))
.Returns(Task.FromResult<object>(42))
.Verifiable();
// Act
content.ReadAsAsync<int>(new[] { formatter.Object }, formatterLogger, token).Wait();
// Assert
formatter.Verify();
}