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


C# Http.HttpServer类代码示例

本文整理汇总了C#中System.Web.Http.HttpServer的典型用法代码示例。如果您正苦于以下问题:C# HttpServer类的具体用法?C# HttpServer怎么用?C# HttpServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpServer类属于System.Web.Http命名空间,在下文中一共展示了HttpServer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AttriubteRouting_SelectsExpectedControllerAndAction

        [InlineData("GET", "http://localhost/Customers(12)/NS.SpecialCustomer/NS.GetSalary()", "GetSalaryFromSpecialCustomer_12")] // call function on derived entity type
        public async Task AttriubteRouting_SelectsExpectedControllerAndAction(string method, string requestUri,
            string expectedResult)
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();

            var controllers = new[] { typeof(CustomersController), typeof(MetadataAndServiceController), typeof(OrdersController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers));

            HttpConfiguration config = new HttpConfiguration();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Services.Replace(typeof(IAssembliesResolver), resolver);

            config.MapODataServiceRoute("odata", "", model.Model);

            HttpServer server = new HttpServer(config);
            config.EnsureInitialized();

            HttpClient client = new HttpClient(server);
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            if (!response.IsSuccessStatusCode)
            {
                Assert.False(true, await response.Content.ReadAsStringAsync());
            }
            var result = await response.Content.ReadAsAsync<AttributeRoutingTestODataResponse>();
            Assert.Equal(expectedResult, result.Value);
        }
开发者ID:richarddwelsh,项目名称:aspnetwebstack,代码行数:33,代码来源:AttributeRoutingTest.cs

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

示例3: Configuration

		public void Configuration(IAppBuilder owinAppBuilder)
        {
			ConfigureAuth(owinAppBuilder);

			// DependencyInjection config
			_container.RegisterModules(new ODataServiceModule(), new IocConfig());

			// Add Web API to the Owin pipeline
			HttpConfiguration webApiConfig = new HttpConfiguration();
#if DEBUG
			webApiConfig.EnableSystemDiagnosticsTracing();
#endif
			webApiConfig.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(_container);
			HttpServer webApiServer = new HttpServer(webApiConfig);
			EntityRepositoryConfig.ConfigureODataService(webApiServer);

			// Map routes using class attributes
			webApiConfig.MapHttpAttributeRoutes();

			owinAppBuilder.UseWebApi(webApiServer);

			// Verify that DI config is valid; and initialize everything
			_container.Verify();

        }
开发者ID:mdabbagh88,项目名称:ODataServer,代码行数:25,代码来源:Startup.cs

示例4: SimpleHelloWorldController

        public static void SimpleHelloWorldController()
        {
            using (var config = new HttpConfiguration())
            using (var server = new HttpServer(config))
            using (var client = new HttpClient(server))
            {
                TraceConfig.Register(config);

                // Controllers are identified through the routing mechanism.
                // Web API includes a convenient extension method to the
                // HttpRouteCollection type, which is exposed as the
                // HttpConfiguration.Routes property. We will use the default
                // uri template and map it using the `MapHttpRoute` extension method.
                // If you have worked with MVC, this will be very familiar.
                // In a larger project, this would most likely be defined in
                // your Global.asax or WebApiConfig.cs file.
                config.Routes.MapHttpRoute(
                    name: "Api",
                    routeTemplate: "api/{controller}"
                );

                using (var response = client.GetAsync("http://example.org/api/helloworld").Result)
                {
                    var body = response.Content.ReadAsStringAsync().Result;
                    Helpers.AssertEquality("\"Hello, ApiController!\"", body);
                }
            }
        }
开发者ID:WebApiContrib,项目名称:WebApiKoans,代码行数:28,代码来源:AboutControllers.cs

示例5: Log_Simple_Request_Test_Should_Log_Request_And_Response

        public void Log_Simple_Request_Test_Should_Log_Request_And_Response()
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { id = RouteParameter.Optional });

            var dummyRepository = new DummyLoggingRepository();
            config.MessageHandlers.Add(new LoggingHandler(dummyRepository));
            config.MessageHandlers.Add(new EncodingHandler());

            var server = new HttpServer(config);
            var client = new HttpClient(new EncodingHandler(server));
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var content = new List<Contact>();
            var c = new Contact { Id = 1, Birthday = DateTime.Now.AddYears(-20) };
            content.Add(c);

            var request = new HttpRequestMessage();
            request.Content = new ObjectContent(typeof(List<Contact>), content, config.Formatters.JsonFormatter);
            client.PostAsync("http://anything/api/contacts", request.Content).ContinueWith(task =>
            {
                var response = task.Result;
                Assert.IsNotNull(response);
                Assert.AreEqual(2, dummyRepository.LogMessageCount);
                Assert.IsTrue(dummyRepository.HasRequestMessageTypeBeenReceived, "No request message has been logged");
                Assert.IsTrue(dummyRepository.HasResponseMessageTypeBeenReceived, "No Response message has been received");
            });
        }
开发者ID:andreabalducci,项目名称:WebAPIContrib,代码行数:29,代码来源:LoggingHandlerTests.cs

示例6: ChatHistoryShouldReturnNotFoundIfNoUsername

        public void ChatHistoryShouldReturnNotFoundIfNoUsername()
        {
            var controller = typeof(MessageController);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               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/Message/History"),
                    Method = HttpMethod.Get
                };

                var result = httpInvoker.SendAsync(request, CancellationToken.None).Result;
                Assert.AreEqual(HttpStatusCode.NotFound, result.StatusCode);
            }
        }
开发者ID:deyantodorov,项目名称:Zeus-WebServicesCould-TeamWork,代码行数:28,代码来源:MessageIntegrationTest.cs

示例7: WindsorResolver_Resolves_Registered_ContactRepository_Through_ContactsController_Test

        public void WindsorResolver_Resolves_Registered_ContactRepository_Through_ContactsController_Test()
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("default",
                "api/{controller}/{id}", new { id = RouteParameter.Optional });

            using (var container = new WindsorContainer())
            {
                container.Register(
                    Component.For<IContactRepository>().Instance(new InMemoryContactRepository()),
                    Component.For<ContactsController>().ImplementedBy<ContactsController>());

                config.DependencyResolver = new WindsorResolver(container);

                var server = new HttpServer(config);
                var client = new HttpClient(server);

				client.GetAsync("http://anything/api/contacts").ContinueWith(task =>
				{
					var response = task.Result.Content.ReadAsAsync<List<Contact>>().Result;
					Assert.IsNotNull(response[1]);


				});
            }
        }
开发者ID:kalyanraman,项目名称:WebApiContrib.IoC.CastleWindsor,代码行数:26,代码来源:DependencyInjectionTests.cs

示例8: ODataSingletonQueryOptionTest

 public ODataSingletonQueryOptionTest()
 {
     _configuration = new HttpConfiguration();
     _configuration.Routes.MapODataServiceRoute("odata", "odata", GetEdmModel());
     HttpServer server = new HttpServer(_configuration);
     _client = new HttpClient(server);
 }
开发者ID:nicholaspei,项目名称:aspnetwebstack,代码行数:7,代码来源:ODataSingletonQueryOptionTest.cs

示例9: Configuration

		/// <summary>
		/// Configure all the OWIN modules that participate in each request.
		/// </summary>
		/// <param name="app">The OWIN appBuilder</param>
		/// <remarks>
		/// The order of configuration is IMPORTANT - it sets the sequence of the request processing pipeline.
		/// </remarks>
		public void Configuration(IAppBuilder app)
		{
#if DEBUG
			// Debug builds get full call stack in error pages.
			app.Properties["host.AppMode"] = "development";
#else
			app.Properties["host.AppMode"] = "release";
#endif

			// DependencyInjection config
			var diContainer = new Container { Options = { AllowOverridingRegistrations = true } };
			diContainer.RegisterModules(new ODataServiceModule(), new AppModule());

			// Configure logging
			ConfigureOwinLogging(app, diContainer);

			// Web API config
			var webApiConfig = new HttpConfiguration();
			webApiConfig.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(diContainer);

			// Map routes using class attributes
			webApiConfig.MapHttpAttributeRoutes();

			HttpServer webApiServer = new HttpServer(webApiConfig);
			WebApiConfig.ConfigureODataService(webApiConfig, webApiServer);

			app.UseWebApi(webApiServer);
		}
开发者ID:mdabbagh88,项目名称:ODataServer,代码行数:35,代码来源:OwinStartup.cs

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

示例11: RegisterTrippin

 public static async void RegisterTrippin(
     HttpConfiguration config, HttpServer server)
 {
     await config.MapRestierRoute<TrippinApi>(
         "TrippinApi", "api/Trippin",
         new RestierBatchHandler(server));
 }
开发者ID:adestis-mh,项目名称:RESTier,代码行数:7,代码来源:WebApiConfig.cs

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

示例13: BadClient

 public BadClient(HttpServer server, ITestOutputHelper output)
 {
     client = new HttpClient(new RequestLogger(output, true, server), false)
     {
         BaseAddress = new Uri("http://bad-client-based")
     };
 }
开发者ID:jochenz,项目名称:unit-testing-restful-services,代码行数:7,代码来源:BadClient.cs

示例14: BasicAuthentication

        public static void BasicAuthentication()
        {
            using (var config = new HttpConfiguration())
            using (var server = new HttpServer(config))
            using (var client = new HttpClient(server))
            {
                config.Routes.MapHttpRoute(
                    name: "Api",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new {id = RouteParameter.Optional}
                );

                var authConfig = new AuthenticationConfiguration
                {
                    InheritHostClientIdentity = true,
                    ClaimsAuthenticationManager = FederatedAuthentication
                        .FederationConfiguration
                        .IdentityConfiguration
                        .ClaimsAuthenticationManager
                };

                // You can setup authentication against membership:
                //authConfig.AddBasicAuthentication((username, password) =>
                //    Membership.ValidateUser(username, password));
                authConfig.AddBasicAuthentication((username, password) =>
                    username == Helpers.__ && password == Helpers.__);

                config.MessageHandlers.Add(new AuthenticationHandler(authConfig));

                client.DefaultRequestHeaders.Authorization =
                    new BasicAuthenticationHeaderValue("happy", "holidays");
                using (var response = client.GetAsync("http://go.com/api/authenticationkoan").Result)
                    Helpers.AssertEquality(HttpStatusCode.OK, response.StatusCode);
            }
        }
开发者ID:sara62,项目名称:WebApiKoans,代码行数:35,代码来源:AboutAuthentication.cs

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


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