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


C# HttpSelfHostServer.CloseAsync方法代码示例

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


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

示例1: Main

        static void Main(string[] args)
        {
            HttpSelfHostServer server = null;
            try
            {
                // 设置selfhost
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);

                //配置(config);
                //清除xml格式,设置Json格式
                config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
                config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
                //设置路由
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
                // 创建服务
                server = new HttpSelfHostServer(config);

                // 开始监听
                server.OpenAsync().Wait();
                Console.WriteLine("Listening on " + _baseAddress);
                Console.WriteLine("Web API host started...");
                //输入exit按Enter結束httpServer
                string line = null;
                do
                {
                    line = Console.ReadLine();
                }
                while (line != "exit");
                //结束连接
                server.CloseAsync().Wait();
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
                Console.WriteLine("Hit ENTER to exit...");
                Console.ReadLine();
            }
            finally
            {
                if (server != null)
                {
                    // Stop listening
                    server.CloseAsync().Wait();
                }
            }
        }
开发者ID:chenyk0317,项目名称:BlogSelfHostWebAPI,代码行数:50,代码来源:Program.cs

示例2: Main

        static void Main(string[] args)
        {
            var port = ConfigurationManager.AppSettings["Port"] ?? "8080";
            var hostname = ConfigurationManager.AppSettings["Hostname"] ?? "localhost";

            //The url that the service can be called on
            var serviceUrl = string.Format("http://{0}:{1}", hostname, port);

            //Service configuration
            var config = new HttpSelfHostConfiguration(serviceUrl);

            //Add routes to controllers
            config.Routes.MapHttpRoute("DefaultApi ", "api/{controller}/{id}", new { id = RouteParameter.Optional });

            //Writes list of available mediatype formatters to console
            Console.WriteLine("{0}{1}", "Registered media type formatters:\n", string.Join("\n", config.Formatters.Select(x => x.GetType())));

            //Initialize server
            _selfHostServerServer = new HttpSelfHostServer(config);

            //Start server
            _selfHostServerServer.OpenAsync().Wait();
            Console.WriteLine("{1}Self hosting server is running on: {0}", serviceUrl, Environment.NewLine);
            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();

            //Wires up application close handler
            AppDomain.CurrentDomain.ProcessExit += (s, e) =>
                                                       {
                                                           //Close server
                                                           _selfHostServerServer.CloseAsync();
                                                           _selfHostServerServer.Dispose();
                                                       };
        }
开发者ID:paulinfrancis,项目名称:WebApiDemo,代码行数:34,代码来源:Program.cs

示例3: Main

        static void Main(string[] args)
        {
            var baseurl = new Uri("http://localhost:9000/");
            var config = new HttpSelfHostConfiguration(baseurl);

            //config.MessageHandlers.Add(new GitHubApiRouter(baseurl));

            //config.Routes.Add("default", new TreeRoute("",new TreeRoute("home").To<HomeController>(),
            //                                              new TreeRoute("contact",
            //                                                        new TreeRoute("{id}",
            //                                                            new TreeRoute("address",
            //                                                                 new TreeRoute("{addressid}").To<ContactAddressController>())
            //                                                        ).To<ContactController>())
            //                                              )
            //                  );

            var route = new TreeRoute("api");
            route.AddWithPath("home", r => r.To<HomeController>());
            route.AddWithPath("contact/{id}",r => r.To<ContactController>());
            route.AddWithPath("contact/{id}/adddress/{addressid}", r => r.To<ContactAddressController>());
            route.AddWithPath("act/A", r => r.To<ActionController>().ToAction("A"));
            route.AddWithPath("act/B", r => r.To<ActionController>().ToAction("B"));

            config.Routes.Add("default", route);

            var host = new HttpSelfHostServer(config);
            host.OpenAsync().Wait();

            Console.WriteLine("Host open.  Hit enter to exit...");

            Console.Read();

            host.CloseAsync().Wait();
        }
开发者ID:darrelmiller,项目名称:ApiRouter,代码行数:34,代码来源:Program.cs

示例4: Main

 static void Main(string[] args)
 {
     HttpSelfHostServer server = null;
     try {
         // Set up server configuration
         HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(BaseAddress);
         config.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{id}",
             defaults: new { id = RouteParameter.Optional }
         );
         // Create server
         server = new HttpSelfHostServer(config);
         // Start listening
         server.OpenAsync().Wait();
         Console.WriteLine("Listening on " + BaseAddress);
         Console.ReadLine();
     }
     catch (Exception e) {
         Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
         Console.WriteLine("Hit ENTER to exit...");
         Console.ReadLine();
     }
     finally {
         if (server != null) {
             // Stop listening
             server.CloseAsync().Wait();
         }
     }
 }
开发者ID:djsolid,项目名称:win8-ws-samples,代码行数:30,代码来源:Program.cs

示例5: Main

        private static void Main(string[] args) {
            string prefix = "http://localhost:8080";
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(prefix);
            config.Routes.MapHttpRoute("Default", "{controller}/{action}");

            // Append our custom valueprovider to the list of value providers.
            config.Services.Add(typeof (ValueProviderFactory), new HeaderValueProviderFactory());

            HttpSelfHostServer server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();

            try {
                // HttpClient will make the call, but won't set the headers for you. 
                HttpClient client = new HttpClient();
                var response = client.GetAsync(prefix + "/ValueProviderTest/GetStuff?id=20").Result;

                // Browsers will set the headers. 
                // Loop. You can hit the request via: http://localhost:8080/Test2/GetStuff?id=40
                while (true) {
                    Thread.Sleep(1000);
                    Console.Write(".");
                }
            }
            finally {
                server.CloseAsync().Wait();
            }
        }
开发者ID:tugberkugurlu,项目名称:ProWebAPI.Samples,代码行数:27,代码来源:Program.cs

示例6: Main

        static void Main(string[] args)
        {
            HttpSelfHostServer server = null;
            try
            {
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);
                config.HostNameComparisonMode = HostNameComparisonMode.Exact;

                // Register default route
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}"
                );

                server = new HttpSelfHostServer(config);
                server.OpenAsync().Wait();
                Console.WriteLine("Listening on " + baseAddress);
                Console.WriteLine("Hit ENTER to exit...");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
                Console.WriteLine("Hit ENTER to exit...");
                Console.ReadLine();
            }
            finally
            {
                if (server != null)
                {
                    server.CloseAsync().Wait();
                }
            }
        }
开发者ID:ericziko,项目名称:edge,代码行数:34,代码来源:Program.cs

示例7: Main

        public static void Main(string[] args)
        {


            HttpSelfHostServer server = null;
            try
            {
                var config = new HttpSelfHostConfiguration("http://localhost:3002/")
                {
                };
                //config.Formatters.Add(new HtmlMediaTypeFormatter());
                var todoList = new Application();
                config.Routes.Add("Noodles", config.Routes.CreateRoute("{*path}",
                    new HttpRouteValueDictionary("route"),
                    constraints: null,
                    dataTokens: null,
                    handler: new NoodlesHttpMessageHandler((r) => todoList)
                    ));
                server = new HttpSelfHostServer(config);

                server.OpenAsync().Wait();

                Console.WriteLine("Hit ENTER to exit");
                Console.ReadLine();
            }
            finally
            {
                if (server != null)
                {
                    server.CloseAsync().Wait();
                }
            }


        }
开发者ID:genoher,项目名称:Noodles,代码行数:35,代码来源:Program.cs

示例8: SendJsonGetCode

        public static HttpStatusCode SendJsonGetCode(string routeTemp, string uri, string json)
        {
            HttpStatusCode actualHttpCode;

            HttpSelfHostConfiguration config
                = new HttpSelfHostConfiguration("http://localhost/");
            config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: routeTemp
                );

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            using (HttpClient client = getJsonClient())
            {
                server.OpenAsync().Wait();
                using (HttpRequestMessage request =
                    getJsonRequest(HttpMethod.Post, uri, json))
                using (HttpResponseMessage response = client.SendAsync(request).Result)
                {
                    actualHttpCode = response.StatusCode;
                }
                server.CloseAsync().Wait();
            }
            return actualHttpCode;
        }
开发者ID:pacholik,项目名称:driving_scools_server,代码行数:25,代码来源:AssertHelper.cs

示例9: Main

        public static void Main(string[] args)
        {
            HttpSelfHostServer server = null;
            try
            {
                var config = new HttpSelfHostConfiguration("http://localhost:3002/")
                {
                    MaxReceivedMessageSize = 1024*1024*1024,
                    TransferMode = TransferMode.Streamed,
                    MessageHandlers =
                    {
                        new ForwardProxyMessageHandler()
                    }
                };

                server = new HttpSelfHostServer(config);

                server.OpenAsync().Wait();

                Console.WriteLine("Hit ENTER to exit");
                Console.ReadLine();
            }
            finally
            {
                if (server != null)
                {
                    server.CloseAsync().Wait();
                }
            }
        }
开发者ID:D3-LucaPiombino,项目名称:WebAPI-Proxy,代码行数:30,代码来源:Program.cs

示例10: Body_WithSingletonControllerInstance_Fails

        public void Body_WithSingletonControllerInstance_Fails()
        {
            // Arrange
            HttpClient httpClient = new HttpClient();
            string baseAddress = "http://localhost";
            string requestUri = baseAddress + "/Test";
            HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration(baseAddress);
            configuration.Routes.MapHttpRoute("Default", "{controller}", new { controller = "Test" });
            configuration.ServiceResolver.SetService(typeof(IHttpControllerFactory), new MySingletonControllerFactory());
            HttpSelfHostServer host = new HttpSelfHostServer(configuration);
            host.OpenAsync().Wait();
            HttpResponseMessage response = null;

            try
            {
                // Act
                response = httpClient.GetAsync(requestUri).Result;
                response = httpClient.GetAsync(requestUri).Result;
                response = httpClient.GetAsync(requestUri).Result;

                // Assert
                Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                }
            }

            host.CloseAsync().Wait();
        }
开发者ID:douchedetector,项目名称:mvc-razor,代码行数:33,代码来源:CustomControllerFactoryTest.cs

示例11: Get_RequestCorrectCourseId_GetCorrectValues

        public void Get_RequestCorrectCourseId_GetCorrectValues()
        {
            int actualCarId;            
            string actualZnacka;
            string actualModel;
            string actualSPZ;
            string actualVIN;
            int actualPocatecniStavKm;
            int actualRokVyroby;
            string actualPosledniSTK;
            int actualAutoskolaId;
            string actualTyp;
            int actualNajetoKm;
            int actualPrumernaSpotreba;

            HttpSelfHostConfiguration config
                = new HttpSelfHostConfiguration("http://localhost/");
            config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: "{controller}/{id}"
                );
            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            using (HttpClient client = new HttpClient())
            {
                server.OpenAsync().Wait();
                using (HttpRequestMessage request =
                    new HttpRequestMessage(HttpMethod.Get, "http://localhost/vozidla/9"))
                using (HttpResponseMessage response = client.SendAsync(request).Result)
                {
                    string json = response.Content.ReadAsStringAsync().Result;
                    dynamic data = JObject.Parse(json);
                    actualCarId = data.vozidlo_id;                    
                    actualZnacka = data.znacka;
                    actualModel = data.model;
                    actualSPZ = data.spz;
                    actualVIN = data.vin;
                    actualPocatecniStavKm = data.pocatecni_stav_km;
                    actualRokVyroby = data.rok_vyroby;
                    actualPosledniSTK = data.posledni_stk;
                    actualAutoskolaId = data.autoskola_id;
                    actualTyp = data.vozidlo_typ;
                    actualNajetoKm = data.pocet_km;
                    actualPrumernaSpotreba = data.prumerna_spotreba;
                }
                server.CloseAsync().Wait();
            }
            Assert.AreEqual(9, actualCarId);
            Assert.AreEqual("Škoda",actualZnacka);
            Assert.AreEqual("Octavia", actualModel);
            Assert.AreEqual("3E8 3853", actualSPZ);
            Assert.AreEqual("FG5464RTV5432AF5F", actualVIN);
            Assert.AreEqual(8832, actualPocatecniStavKm);
            Assert.AreEqual(2007, actualRokVyroby);
            Assert.AreEqual(new DateTime(2013, 11, 25).ToString("MM/dd/yyyy HH:mm:ss"), actualPosledniSTK);
            Assert.AreEqual(1, actualAutoskolaId);
            Assert.AreEqual("osobni", actualTyp);
            Assert.AreEqual(8832 + 36, actualNajetoKm);
            Assert.AreEqual(6, actualPrumernaSpotreba);
        }
开发者ID:pacholik,项目名称:driving_scools_server,代码行数:59,代码来源:VozidlaControllerTests.cs

示例12: Main

        static void Main(string[] args)
        {
            HttpSelfHostServer server = null;

            try
            {
                // Set up server configuration
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
                config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

                // Add $format support
                config.MessageHandlers.Add(new FormatQueryMessageHandler());

                // Add NavigationRoutingConvention2 to support POST, PUT, PATCH and DELETE on navigation property
                var conventions = ODataRoutingConventions.CreateDefault();
                conventions.Insert(0, new CustomNavigationRoutingConvention());

                // Enables OData support by adding an OData route and enabling querying support for OData.
                // Action selector and odata media type formatters will be registered in per-controller configuration only
                config.Routes.MapODataRoute(
                    routeName: "OData",
                    routePrefix: null,
                    model: ModelBuilder.GetEdmModel(),
                    pathHandler: new DefaultODataPathHandler(),
                    routingConventions: conventions);

                // Enable queryable support and allow $format query
                config.EnableQuerySupport(new QueryableAttribute { 
                    AllowedQueryOptions = AllowedQueryOptions.Supported | AllowedQueryOptions.Format });

                // To disable tracing in your application, please comment out or remove the following line of code
                // For more information, refer to: http://www.asp.net/web-api
                config.EnableSystemDiagnosticsTracing();

                config.Filters.Add(new ModelValidationFilterAttribute());

                // Create server
                server = new HttpSelfHostServer(config);

                // Start listening
                server.OpenAsync().Wait();
                Console.WriteLine("Listening on " + _baseAddress);
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
            }
            finally
            {
                Console.WriteLine("Hit ENTER to exit...");
                Console.ReadLine();

                if (server != null)
                {
                    // Stop listening
                    server.CloseAsync().Wait();
                }
            }
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:59,代码来源:Program.cs

示例13: Main

        public static void Main(string[] args)
        {
            HttpSelfHostServer server = null;
            try
            {
                // Set up server configuration
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
                config.HostNameComparisonMode = HostNameComparisonMode.Exact;
                config.Formatters.JsonFormatter.Indent = true;
                config.Formatters.XmlFormatter.Indent = true;
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );

                // Create server
                server = new HttpSelfHostServer(config);

                // Start listening
                server.OpenAsync().Wait();
                Console.WriteLine("Listening on " + _baseAddress);

                Console.WriteLine("*******************************");
                Console.WriteLine("POSTing a valid customer");
                Console.WriteLine("*******************************");
                PostValidCustomer();

                Console.WriteLine("*******************************");
                Console.WriteLine("POSTing a customer with a missing ID");
                Console.WriteLine("*******************************");
                PostCustomerMissingID();

                Console.WriteLine("*******************************");
                Console.WriteLine("POSTing a customer with negative ID and invalid phone number");
                Console.WriteLine("*******************************");
                PostInvalidCustomerUsingJson();

                Console.WriteLine("*******************************");
                Console.WriteLine("POSTing a customer with negative ID and invalid phone number using XML");
                Console.WriteLine("*******************************");
                PostInvalidCustomerUsingXml();
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
            }
            finally
            {
                if (server != null)
                {
                    // Stop listening
                    server.CloseAsync().Wait();
                }
                Console.WriteLine("Hit ENTER to exit...");
                Console.ReadLine();
            }
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:58,代码来源:Program.cs

示例14: Main

        static void Main(string[] args)
        {
            HttpSelfHostServer server = null;

            try
            {
                // Configure Server Settings
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);

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

                // Create Server
                server = new HttpSelfHostServer(config);

                //Start Listening
                server.OpenAsync().Wait();
                Console.WriteLine("Listening on " + _baseAddress);

                Console.WriteLine("Press Enter to exit...");
                Console.WriteLine();

                // Call the web Api and display the result
                HttpClient client = new HttpClient();
                client.GetStringAsync(_baseAddress).ContinueWith(
                    getTask =>
                    {
                        if (getTask.IsCanceled)
                            Console.WriteLine("Request was canceled");

                        else if (getTask.IsFaulted)
                            Console.WriteLine("Request failed: {0}", getTask.Exception);

                        else
                            Console.WriteLine("Client reieved: {0}", getTask.Result);
                    });

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Couln't start Server: {0}", ex.GetBaseException().Message);
                Console.WriteLine("Press Enter to exit..");
                Console.ReadLine();
            }
            finally
            {
                if (server != null)
                {
                    // Stop Listening
                    server.CloseAsync().Wait();
                }
            }
        }
开发者ID:viperium,项目名称:WatchDogWP8,代码行数:55,代码来源:Program.cs

示例15: Main

        static void Main(string[] args)
        {
            HttpSelfHostServer server = null;

            try
            {
                // Create configuration
                var config = new HttpSelfHostConfiguration(_baseAddress);
                config.HostNameComparisonMode = HostNameComparisonMode.Exact;

                // Turn on streaming in selfhost for both requests and responses.
                // if you do this in ASP.NET then please see this blog from @filip_woj for details 
                // on how to turn off buffering in ASP.NET: 
                // http://www.strathweb.com/2012/09/dealing-with-large-files-in-asp-net-web-api/
                config.TransferMode = TransferMode.Streamed;

                // Set max received size to 10G
                config.MaxReceivedMessageSize = 10L * 1024 * 1024 * 1024;

                // Set receive and send timeout to 20 mins
                config.ReceiveTimeout = TimeSpan.FromMinutes(20);
                config.SendTimeout = TimeSpan.FromMinutes(20);

                // Add a route
                config.Routes.MapHttpRoute(
                  name: "default",
                  routeTemplate: "api/{controller}/{id}",
                  defaults: new { controller = "Home", id = RouteParameter.Optional });

                // Create server
                server = new HttpSelfHostServer(config);

                // Start server
                server.OpenAsync().Wait();

                Console.WriteLine("Server listening at {0}", _baseAddress);
                Console.WriteLine("Hit ENTER to exit");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
                Console.WriteLine("Hit ENTER to exit...");
                Console.ReadLine();
            }
            finally
            {
                if (server != null)
                {
                    // Close server
                    server.CloseAsync().Wait();
                }
            }
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:54,代码来源:Program.cs


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