示例#1
0
        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();
        }
 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
0
        public async Task ReadAsAsync_type_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
            await content.ReadAsAsync(
                typeof(int),
                new[] { formatter.Object },
                formatterLogger,
                token
                );

            // Assert
            formatter.Verify();
        }
        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());
        }
        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());
        }
示例#6
0
        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));
        }
        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();
        }