当前位置: 首页>>代码示例>>C#>>正文


C# HttpMessageInvoker.SendAsync方法代码示例

本文整理汇总了C#中System.Net.Http.HttpMessageInvoker.SendAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpMessageInvoker.SendAsync方法的具体用法?C# HttpMessageInvoker.SendAsync怎么用?C# HttpMessageInvoker.SendAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Http.HttpMessageInvoker的用法示例。


在下文中一共展示了HttpMessageInvoker.SendAsync方法的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: ShouldGenerateAuthHeader

        public void ShouldGenerateAuthHeader()
        {
            var credential = new HawkCredential
            {
                Id = "123",
                Algorithm = "sha256",
                Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                User = "steve"
            };

            var nonce = "123456";

            var date = DateTime.UtcNow;
            var ts = Hawk.ConvertToUnixTimestamp(date).ToString();

            var handler = new HawkClientMessageHandler(new DummyHttpMessageHandler(),
                credential, "hello", date, nonce);

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");

            var invoker = new HttpMessageInvoker(handler);
            invoker.SendAsync(request, new CancellationToken());

            var mac = Hawk.CalculateMac(request.Headers.Host, request.Method.ToString(), request.RequestUri,
                "hello", ts, nonce, credential, "header");

            var parameter = string.Format("id=\"{0}\", ts=\"{1}\", nonce=\"{2}\", mac=\"{3}\", ext=\"{4}\"",
                credential.Id, ts, nonce, mac, "hello");

            Assert.IsNotNull(request.Headers.Authorization);
            Assert.AreEqual("Hawk", request.Headers.Authorization.Scheme);
            Assert.AreEqual(parameter,
                request.Headers.Authorization.Parameter);
        }
开发者ID:linkypi,项目名称:hawknet,代码行数:34,代码来源:HawkClientMessageHandlerFixture.cs

示例3: 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

示例4: 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

示例5: SendAsync_Preflight_ReturnsAllowMethodsAndAllowHeaders

        public void SendAsync_Preflight_ReturnsAllowMethodsAndAllowHeaders(string requestedMethod, string expectedOrigin, string requestedHeaders)
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute("default", "{controller}");
            HttpServer server = new HttpServer(config);
            CorsMessageHandler corsHandler = new CorsMessageHandler(config);
            corsHandler.InnerHandler = server;
            HttpMessageInvoker invoker = new HttpMessageInvoker(corsHandler);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, "http://localhost/sample");
            request.SetConfiguration(config);
            request.Headers.Add(CorsConstants.Origin, "http://localhost");
            request.Headers.Add(CorsConstants.AccessControlRequestMethod, requestedMethod);
            request.Headers.Add(CorsConstants.AccessControlRequestHeaders, requestedHeaders);

            HttpResponseMessage response = invoker.SendAsync(request, CancellationToken.None).Result;
            string origin = response.Headers.GetValues(CorsConstants.AccessControlAllowOrigin).FirstOrDefault();
            string allowMethod = response.Headers.GetValues(CorsConstants.AccessControlAllowMethods).FirstOrDefault();
            string[] allowHeaders = response.Headers.GetValues(CorsConstants.AccessControlAllowHeaders).FirstOrDefault().Split(',');
            string[] requestedHeaderArray = requestedHeaders.Split(',');

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(expectedOrigin, origin);
            Assert.Equal(requestedMethod, allowMethod);
            foreach (string requestedHeader in requestedHeaderArray)
            {
                Assert.Contains(requestedHeader, allowHeaders);
            }
        }
开发者ID:normalian,项目名称:aspnetwebstack,代码行数:28,代码来源:CorsMessageHandlerTest.cs

示例6: ShouldFailOnInvalidCredentials

        public void ShouldFailOnInvalidCredentials()
        {
            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(), (id) =>
            {
                return new HawkCredential
                    {
                        Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                        User = "steve"
                    };
            });

            var invoker = new HttpMessageInvoker(handler);

            var ts = Hawk.ConvertToUnixTimestamp(DateTime.Now).ToString();

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");
            request.Headers.Authorization = new AuthenticationHeaderValue("Hawk", "id = \"456\", ts = \"" + ts + "\", nonce=\"k3j4h2\", mac = \"qrP6b5tiS2CO330rpjUEym/USBM=\", ext = \"hello\"");
            request.Headers.Host = "localhost";

            var response = invoker.SendAsync(request, new CancellationToken())
                .Result;

            Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
            Assert.AreEqual("Invalid credentials", response.ReasonPhrase);
        }
开发者ID:nordineb,项目名称:hawknet,代码行数:25,代码来源:HawkMessageHandlerFixture.cs

示例7: 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

示例8: 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

示例9: 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

示例10: 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

示例11: ByProjectShouldReturnCorrectResponse

        public void ByProjectShouldReturnCorrectResponse()
        {
            // Required by the HttpServer to find controller in another assembly
            var controller = typeof(CommitsController);

            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/Commits/ByProject/1"),
                    Method = HttpMethod.Get
                };

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

                Assert.IsNotNull(result);
                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            }
        }
开发者ID:resnick1223,项目名称:Web-Services-and-Cloud,代码行数:32,代码来源:CommitsIntegrationTests.cs

示例12: 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

示例13: 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

示例14: 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

示例15: 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


注:本文中的System.Net.Http.HttpMessageInvoker.SendAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。