當前位置: 首頁>>代碼示例>>C#>>正文


C# Http.HttpMessageInvoker類代碼示例

本文整理匯總了C#中System.Net.Http.HttpMessageInvoker的典型用法代碼示例。如果您正苦於以下問題:C# HttpMessageInvoker類的具體用法?C# HttpMessageInvoker怎麽用?C# HttpMessageInvoker使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


HttpMessageInvoker類屬於System.Net.Http命名空間,在下文中一共展示了HttpMessageInvoker類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: ByPostShouldReturnCorrectResponse

        public void ByPostShouldReturnCorrectResponse()
        {
            var controller = typeof(CategoriesController);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
            );

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            var httpServer = new HttpServer(config);
            var httpInvoker = new HttpMessageInvoker(httpServer);

            using (httpInvoker)
            {
                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://test.com/api/categories/1"),
                    Method = HttpMethod.Get
                };

                var result = httpInvoker.SendAsync(request, CancellationToken.None).Result;

                Assert.IsNotNull(result);
            }
        }
開發者ID:Team-Hypnos,項目名稱:Gallery,代碼行數:30,代碼來源:CategoriesIntegrationTests.cs

示例2: HttpCrowDispatcher

 public HttpCrowDispatcher(HttpConfiguration configuration, HttpMessageHandler handler, IEnumerable<string> filteredUrl)
     : base()
 {
     _configuration = configuration;
     _messageInvoker = new HttpMessageInvoker(handler);
     _filteredUrl = filteredUrl ?? new List<string>();
 }
開發者ID:msusur,項目名稱:Crowfx,代碼行數:7,代碼來源:HttpCrowDispatcher.cs

示例3: TestWebApiCanInitialize

        public void TestWebApiCanInitialize()
        {
            HttpServer server = null;
            string controllerResponse = string.Empty;

            Host host = HostFactory.New(configurator =>
            {
                configurator.UseTestHost();

                configurator.Service<SampleService>(s =>
                {
                    s.ConstructUsing(settings => new SampleService());
                    s.WhenStarted((service, control) => service.Start());
                    s.AfterStartingService(() =>
                    {
                        using (var client = new HttpMessageInvoker(server))
                        using (var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Api/Test"))
                        using (var response = client.SendAsync(request, CancellationToken.None).Result)
                            controllerResponse = response.Content.ReadAsStringAsync().Result;
                    });
                    s.WhenStopped((service, control) => service.Stop());
                    s.WebApiEndpoint(api =>
                    {
                        //Use an in-memory server instead of the SelfHost server.
                        api.ServerFactory = uri => new HttpServer(new HttpConfiguration());
                        api.ConfigureRoutes(Configure);
                        server = api.Build();
                    });
                });
            });

            host.Run();

            Assert.AreEqual("42", controllerResponse);
        }
開發者ID:Zero1991,項目名稱:Topshelf.Integrations,代碼行數:35,代碼來源:TopshelfWebApiTests.cs

示例4: SendRequestAsync

        /// <summary>
        /// Sends the ChangeSet request.
        /// </summary>
        /// <param name="invoker">The invoker.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>A <see cref="ChangeSetResponseItem"/>.</returns>
        public override async Task<ODataBatchResponseItem> SendRequestAsync(HttpMessageInvoker invoker, CancellationToken cancellationToken)
        {
            if (invoker == null)
            {
                throw Error.ArgumentNull("invoker");
            }

            cancellationToken.ThrowIfCancellationRequested();

            Dictionary<string, string> contentIdToLocationMapping = new Dictionary<string, string>();
            List<HttpResponseMessage> responses = new List<HttpResponseMessage>();

            try
            {
                foreach (HttpRequestMessage request in Requests)
                {
                    responses.Add(await SendMessageAsync(invoker, request, cancellationToken, contentIdToLocationMapping));
                }
            }
            catch
            {
                foreach (HttpResponseMessage response in responses)
                {
                    if (response != null)
                    {
                        response.Dispose();
                    }
                }
                throw;
            }

            return new ChangeSetResponseItem(responses);
        }
開發者ID:brianly,項目名稱:aspnetwebstack,代碼行數:39,代碼來源:ChangeSetRequestItem.cs

示例5: CallAsyncMethod

 private static async void CallAsyncMethod()
 {
     var expected = new HttpResponseMessage();
     var handler = new AsyncClass() { InnerHandler = new EchoHandler(expected) };
     var invoker = new HttpMessageInvoker(handler, false);
     var actual = await invoker.SendAsync(new HttpRequestMessage(), new CancellationToken());
 }
開發者ID:paolocosta,項目名稱:OpenCoverSample,代碼行數:7,代碼來源:Program.cs

示例6: RunTest

        public static void RunTest(string controllerName, string routeSuffix, HttpRequestMessage request,
            Action<HttpResponseMessage> assert, Action<HttpConfiguration> configurer = null)
        {
            // Arrange
            HttpConfiguration config = new HttpConfiguration() { IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always };

            config.Routes.MapHttpRoute("Default", "{controller}" + routeSuffix, new { controller = controllerName });
            if (configurer != null)
            {
                configurer(config);
            }
            HttpServer server = new HttpServer(config);
            HttpMessageInvoker invoker = new HttpMessageInvoker(server);
            HttpResponseMessage response = null;
            try
            {
                // Act
                response = invoker.SendAsync(request, CancellationToken.None).Result;

                // Assert
                assert(response);
            }
            finally
            {
                request.Dispose();
                if (response != null)
                {
                    response.Dispose();
                }
            }
        }
開發者ID:reza899,項目名稱:aspnetwebstack,代碼行數:31,代碼來源:ScenarioHelper.cs

示例7: Should_reject_an_invalid_request

        public void Should_reject_an_invalid_request()
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "http://myApi/api/somePath");
            request.Headers.Date = new DateTimeOffset(DateTime.UtcNow);
            request.Content = new StringContent("{'A':'b'}");
            request.Headers.Authorization = new AuthenticationHeaderValue(Configuration.AuthenticationScheme,
                string.Format("{0}:{1}", "1234", "bad hash value"));

            request.Content.Headers.ContentMD5 = Encoding.UTF8.GetBytes("anotherBadHash");

            var innerhandler = new FakeInnerHandler
            {
                Message = new HttpResponseMessage(HttpStatusCode.OK)
            };
            var client = new HttpMessageInvoker(new HmacAuthenticationHandler(
                        new ApiKeyRepository(),
                        new CanonicalRepresentationBuilder(),
                        new HmacSignatureCalculator())
            {
                InnerHandler = innerhandler
            });

            var message = client.SendAsync(request, new CancellationToken(false)).Result;
            Assert.AreEqual(message.StatusCode, HttpStatusCode.Unauthorized);
        }
開發者ID:rbanks54,項目名稱:HMAC.Sample,代碼行數:25,代碼來源:ServerSideHandler.cs

示例8: GetResponse

        public static async Task<HttpResponseMessage> GetResponse(
            string requestUri,
            HttpMethod httpMethod,
            HttpContent requestContent,
            Action<HttpConfiguration, HttpServer> registerOData,
            IEnumerable<KeyValuePair<string, string>> headers = null)
        {
            using (HttpConfiguration config = new HttpConfiguration())
            {
                using (HttpServer server = new HttpServer(config))
                using (HttpMessageInvoker client = new HttpMessageInvoker(server))
                {
                    registerOData(config, server);
                    HttpRequestMessage request = new HttpRequestMessage(httpMethod, requestUri);
                    try
                    {
                        request.Content = requestContent;
                        if (headers != null)
                        {
                            foreach (var header in headers)
                            {
                                request.Headers.Add(header.Key, header.Value);
                            }
                        }

                        return await client.SendAsync(request, CancellationToken.None);
                    }
                    finally
                    {
                        request.DisposeRequestResources();
                        request.Dispose();
                    }
                }
            }
        }
開發者ID:adestis-mh,項目名稱:RESTier,代碼行數:35,代碼來源:ODataTestHelpers.cs

示例9: IndexShouldNotThrow

        public void IndexShouldNotThrow()
        {
            var controller = typeof(ChatController);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}",
                defaults: new { id = RouteParameter.Optional }
            );

            var httpServer = new HttpServer(config);

            var httpInvoker = new HttpMessageInvoker(httpServer);

            using (httpInvoker)
            {
                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://test.com/api/Chat/Index"),
                    Method= HttpMethod.Get
                };

                var result=httpInvoker.SendAsync(request, CancellationToken.None).Result;

            }
        }
開發者ID:deyantodorov,項目名稱:Zeus-WebServicesCould-TeamWork,代碼行數:29,代碼來源:ChatIntegrationTest.cs

示例10: InvokeAsync

        internal static Task<HttpResponseMessage> InvokeAsync(
            this DelegatingHandler handler, HttpRequestMessage request, CancellationToken cancellationToken = default(CancellationToken)) {

            handler.InnerHandler = new DummyHandler();
            var invoker = new HttpMessageInvoker(handler);
            return invoker.SendAsync(request, cancellationToken);
        }
開發者ID:kinhnv,項目名稱:PingYourPackage,代碼行數:7,代碼來源:DelegatingHandlerExtensions.cs

示例11: http_post

        public async Task http_post()
        {
            //arrange
            var httpConfig = new HttpConfiguration();
            WebApiConfig.Register(httpConfig);
            var url = "http://localhost/api/default";

            //act
            using (var httpServer = new HttpServer(httpConfig))
            using (var client = new HttpMessageInvoker(httpServer))
            {
                using (var request = new HttpRequestMessage(HttpMethod.Post, url))
                {
                    request.Content = new ObjectContent<string>("Johnny", new JsonMediaTypeFormatter());
                    using (var response = await client.SendAsync(request, CancellationToken.None))
                    {
                        var output = await response.Content.ReadAsAsync<string>();

                        //assert
                        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                        Assert.AreEqual("Hello Johnny!", output);
                    }
                }
            }
            
        }
開發者ID:stephenzeng,項目名稱:web-api-2-owin-middleware,代碼行數:26,代碼來源:web_api_tests.cs

示例12: HttpResponseMessage

        public void Test_不是聖誕節的時候_應回傳BadRequest()
        {
            // arrange

            // Step1: 初始化 fakeInnerHandler, 拿來接在欲測試的 messageHandler 後麵
            // 預計的回傳值可以隨便自訂
            var fakeInnerHandler = new FakeInnerHandler
            {
                Message = new HttpResponseMessage(System.Net.HttpStatusCode.OK)
                {
                    Content = new StringContent("Fake inner handler response")
                }
            };

            // Step2: 初始化測試目標,並將 fakeInnerHandler assign 給 InnerHandler 的 property
            var target = new XmasMessageHandler() { InnerHandler = fakeInnerHandler };

            // Step3: MessageHandler 的單元測試,需要透過HttpMessageInvoker來模擬 client 端送 request 進來
            HttpMessageInvoker client = new HttpMessageInvoker(target);

            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/Fake");
            httpRequestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());

            // act
            // Step4: 呼叫HttpMessageInvoker的 SendAsync ,就會先呼叫 target,
            // 當正常執行時,會先呼叫 target 的 SendAsync(), 穿過 target 後,再呼叫 InnerHandler 的 SendAsync()
            var actual = client.SendAsync(httpRequestMessage, new CancellationToken()).Result;

            // assert
            // Step5: 驗證回傳的 StatusCode 是否為 BadRequest
            Assert.AreEqual(HttpStatusCode.BadRequest, actual.StatusCode);
        }
開發者ID:cashwu,項目名稱:TDD,代碼行數:32,代碼來源:XmasMessageHandlerTest.cs

示例13: SendMessageAsync

        /// <summary>
        /// Sends a single OData batch request.
        /// </summary>
        /// <param name="invoker">The invoker.</param>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
        /// <param name="contentIdToLocationMapping">The Content-ID to Location mapping.</param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> SendMessageAsync(HttpMessageInvoker invoker, HttpRequestMessage request, CancellationToken cancellationToken, Dictionary<string, string> contentIdToLocationMapping)
        {
            if (invoker == null)
            {
                throw Error.ArgumentNull("invoker");
            }
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            if (contentIdToLocationMapping != null)
            {
                string resolvedRequestUrl = ContentIdHelpers.ResolveContentId(request.RequestUri.OriginalString, contentIdToLocationMapping);
                request.RequestUri = new Uri(resolvedRequestUrl);

                request.SetODataContentIdMapping(contentIdToLocationMapping);
            }

            HttpResponseMessage response = await invoker.SendAsync(request, cancellationToken);
            ContentIdHelpers.CopyContentIdToResponse(request, response);

            if (contentIdToLocationMapping != null)
            {
                ContentIdHelpers.AddLocationHeaderToMapping(response, contentIdToLocationMapping);
            }

            return response;
        }
開發者ID:KevMoore,項目名稱:aspnetwebstack,代碼行數:37,代碼來源:ODataBatchRequestItem.cs

示例14: GetList_ReturnsListWithHeaders_Always

        public void GetList_ReturnsListWithHeaders_Always()
        {
            // Arrange
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                "Default",
                "{controller}/{action}",
                new
                {
                    controller = "Test",
                    action = "Get"
                });

            var server = new HttpServer(config);

            using (var client = new HttpMessageInvoker(server))
            {
                // Act
                using (var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Test?page=2&per_page=2"))
                using (var response = client.SendAsync(request, CancellationToken.None).Result)
                {
                    // Assert
                    Assert.IsNotNull(response);
                    Assert.AreEqual(response.StatusCode, HttpStatusCode.OK);
                    Assert.AreEqual(response.Headers.GetValues("X-Total-Page-Count").Single(), "7");
                    Assert.AreEqual(response.Headers.GetValues("X-Total-Count").Single(), "2");
                    Assert.AreEqual(response.Headers.GetValues("X-Current-Page").Single(), "2");
                    Assert.AreEqual(response.Headers.GetValues("Link").Single(), "<http://localhost/Test/?page=1&per_page=2>; rel=\"first\", <http://localhost/Test/?page=1&per_page=2>; rel=\"previous\", <http://localhost/Test/?page=3&per_page=2>; rel=\"next\", <http://localhost/Test/?page=7&per_page=2>; rel=\"last\"");
                }
            }
        }
開發者ID:Ado77,項目名稱:NSWRFS.WebAPI.Core,代碼行數:31,代碼來源:BaseApiControllerTest.cs

示例15: SendAsync_CallsControllerExecuteAsyncWithPopulatedControllerContext

        public void SendAsync_CallsControllerExecuteAsyncWithPopulatedControllerContext()
        {
            HttpControllerContext calledContext = null;
            var mockSelector = new Mock<IHttpControllerSelector>();
            var mockDescriptor = new Mock<HttpControllerDescriptor>();
            var mockController = new Mock<IHttpController>();
            var config = new HttpConfiguration();
            config.Services.Replace(typeof(IHttpControllerSelector), mockSelector.Object);
            var request = CreateRequest(config, "http://localhost/api/foo");
            mockSelector.Setup(s => s.SelectController(request))
                        .Returns(mockDescriptor.Object);
            mockDescriptor.Setup(d => d.CreateController(request))
                          .Returns(mockController.Object);
            mockDescriptor.Object.Initialize(config);
            mockController.Setup(c => c.ExecuteAsync(It.IsAny<HttpControllerContext>(), CancellationToken.None))
                          .Callback((HttpControllerContext ctxt, CancellationToken token) => { calledContext = ctxt; });
            var dispatcher = new HttpControllerDispatcher(config);
            var invoker = new HttpMessageInvoker(dispatcher);

            invoker.SendAsync(request, CancellationToken.None).WaitUntilCompleted();

            Assert.NotNull(calledContext);
            Assert.Same(mockController.Object, calledContext.Controller);
            Assert.Same(mockDescriptor.Object, calledContext.ControllerDescriptor);
            Assert.Same(config, calledContext.Configuration);
            Assert.Same(request, calledContext.Request);
            Assert.Same(request.GetRouteData(), calledContext.RouteData);
        }
開發者ID:khorchani,項目名稱:aspnetwebstack,代碼行數:28,代碼來源:HttpControllerDispatcherTest.cs


注:本文中的System.Net.Http.HttpMessageInvoker類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。