Example #1
0
        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();
                }
            }
        }
Example #2
0
        public void Stop()
        {
            LoginMonitor.Quit();

            server.CloseAsync();
            server.Dispose();
        }
Example #3
0
        static async Task RunControlEndpoint(IPEndPoint controlEP)
        {
            var config = new HttpSelfHostConfiguration(
                new UriBuilder(Uri.UriSchemeHttp, "localhost", controlEP.Port).Uri);

            config.Routes.MapHttpRoute("API", "{controller}/{id}", new { id = RouteParameter.Optional });
            var controlServer = new HttpSelfHostServer(config);

            try
            {
                await controlServer.OpenAsync();

                Trace.TraceInformation("Control endpoint listening at {0}", config.BaseAddress);
            }
            catch (Exception exception)
            {
                controlServer.Dispose();
                Trace.TraceError("Control endpoint cannot open, {0}", exception.Message);
                throw;
            }
            await ClosingEvent.Task;

            try
            {
                await controlServer.CloseAsync();
            }
            finally
            {
                controlServer.Dispose();
            }
        }
Example #4
0
 public async void Stop()
 {
     if (selfHost != null)
     {
         await selfHost.CloseAsync();
     }
 }
Example #5
0
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration(ApplicationSettings.apiBaseUrl);

            config.MaxReceivedMessageSize = 1024 * 1024 * 1024;
            config.MessageHandlers.Add(new CorsHandler());
            Routes.RegisterRoutes(config.Routes);
            var apiServer = new HttpSelfHostServer(config);

            apiServer.OpenAsync().Wait();
            var signalrServer = new Server(ApplicationSettings.signalrBaseUrl);

            signalrServer.MapHubs("/signalr");
            signalrServer.Start();

            Helpers.InitializeDocumentStore();
            var itunes = new iTunesAppClass();

            Start(itunes);

            Console.WriteLine("API is avalible at " + ApplicationSettings.apiBaseUrl);
            Console.WriteLine("Singlar Nortifications avalible at " + ApplicationSettings.signalrBaseUrl);
            Console.WriteLine("See http://github.com/osbornm/playr for more information on setup.");
            Console.WriteLine();
            Console.WriteLine("Press any key to stop server...");
            Console.ReadLine();

            // Stop Everything
            apiServer.CloseAsync().Wait();
            signalrServer.Stop();
            Stop(itunes);
            Marshal.ReleaseComObject(itunes);
        }
Example #6
0
 public static void Stop(HttpSelfHostServer p_objServer)
 {
     if (p_objServer != null)
     {
         p_objServer.CloseAsync().Wait();
     }
 }
        static void Main(string[] args)
        {
            // Configuration details
            Uri address = new Uri("http://localhost:60064/");
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address);

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

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

            // Listener
            server.OpenAsync().Wait();
            Console.WriteLine("Inventory controller hosted on " + address);
            Console.WriteLine("Type exit to end the service.");
            while (true)
            {
                var userInput = Console.ReadLine();
                if (userInput.ToLower() == "exit")
                {
                    break;
                }
            }
            server.CloseAsync().Wait();
        }
 public void Stop()
 {
     server.CloseAsync();
     server.Dispose();
     Console.WriteLine("Server stop!" + baseAddress);
     WorkingBD.SaveLog("Сервер остановлен");
 }
Example #9
0
        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>());

            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();
        }
Example #10
0
    private static void Main(string[] args)
    {
        var baseAddress   = new Uri("http://oak:8700/");
        var configuration = new HttpSelfHostConfiguration(baseAddress);
        var router        = new ApiRouter("api", baseAddress);

        // /api/Contacts
        router.Add("Contacts", rcs => rcs.To <ContactsController>());
        // /api/Contact/{contactid}
        router.Add("Contact", rc =>
                   rc.Add("{contactid}", rci => rci.To <ContactController>()));
        // /api/Group/{groupid}
        // /api/Group/{groupid}/Contacts
        router.Add("Group", rg =>
                   rg.Add("{groupid}", rgi => rgi.To <GroupController>()
                          .Add("Contacts", rgc => rgc.To <GroupContactsController>())));

        configuration.MessageHandlers.Add(router);
        var host = new HttpSelfHostServer(configuration);

        host.OpenAsync().Wait();
        Console.WriteLine("Host open.  Hit enter to exit...");
        Console.Read();
        host.CloseAsync().Wait();
    }
Example #11
0
        } //method

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_redirectServer != null)
            {
                AsyncHelper.RunSync(() => _redirectServer.CloseAsync());
            }
        }
Example #12
0
 public void End()
 {
     if (server != null)
     {
         server.CloseAsync().Wait();
     }
 }
Example #13
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var config = new HttpSelfHostConfiguration("http://localhost:8001");

            //注意: 在Vista, Win7/8,預設需以管理者權限執行才能繫結到指定URL,否則要透過以下指令授權
            //開放授權 netsh http add urlacl url=http://+:32767/ user=machine\username
            //移除權限 netsh http delete urlacl url=http://+:32767/
            //設定路由
            config.Routes.MapHttpRoute("API", "{controller}/{action}/{id}", new { id = RouteParameter.Optional });
            config.EnableCors();
            //設定Self-Host Server,由於會使用到網路資源,用using確保會Dispose()加以釋放
            using (var httpServer = new HttpSelfHostServer(config))
            {
                //OpenAsync()屬非同步呼叫,加上Wait()則等待開啟完成才往下執行
                httpServer.OpenAsync().Wait();

                Console.WriteLine("Web API host started...");
                //輸入exit按Enter結束httpServer
                string line = null;
                do
                {
                    line = Console.ReadLine();
                }while (line != "exit");
                //結束連線
                httpServer.CloseAsync().Wait();
            }
        }
Example #14
0
        public async Task Stop()
        {
            await _server.CloseAsync();

            _server.Dispose();
            PhotoCatcher.Instance.Dispose();
        }
Example #15
0
        protected override void OnStop()
        {
            _logger.Info("Try stop");

            if (_server != null)
            {
                _server.CloseAsync().Wait();
            }

            _logger.Info("Api server stop successful");

            _consumer?.Dispose();
            _messageBus.Dispose();

            _sendService.Dispose();

            _logger.Info("Stop successful");

            _logger.Factory.Flush(5000);

            if (LogManager.Configuration != null)
            {
                var allTargets = LogManager.Configuration.AllTargets;
                foreach (var target in allTargets)
                {
                    target.Dispose();
                }
            }
        }
Example #16
0
        static void Main(string[] args)
        {
            Console.WriteLine(@"********* SERVIDOR DIRETORIO ***********");
            Servers.Servidores = new List <CalculadoraPath>();
            var url = default(string);

            IPAddress[] localIps = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (var ipAddress in localIps)
            {
                if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
                {
                    url = ipAddress.ToString();
                }
            }
            var port = default(string);

            Console.WriteLine(@"Informe porta do servidor:");
            port = Console.ReadLine();
            url  = PreparaUrl(url);
            url  = string.Format(url + ":{0}", port);
            var config = new HttpSelfHostConfiguration(url);

            config.Routes.MapHttpRoute("API", "api/{controller}/{action}/{id}",
                                       new { id = RouteParameter.Optional });
            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine(@"Online:");
                Console.WriteLine(url);
                Console.WriteLine(@"Press any key to stop");
                Console.ReadKey();
                server.CloseAsync();
            }
        }
Example #17
0
        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();
                }
            }
        }
Example #18
0
        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();
                }
            }
        }
        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();
                }
            }
        }
Example #20
0
        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();
        }
        public static void Main(string[] args)
        {
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);

            config.EnableCors();

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

            var server = new HttpSelfHostServer(config);

            server.OpenAsync().Wait();

            ProductRepository.Connection();

            Console.WriteLine("Server running on {0}...", _baseAddress);
            Console.WriteLine("Press ENTER to exit...");

            Console.ReadLine();

            server.CloseAsync().Wait();
        }
Example #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="e"></param>
        protected override void OnExit(ExitEventArgs e)
        {
            _server.CloseAsync().Wait();
            _server.Dispose();

            base.OnExit(e);
        }
Example #23
0
        /// <summary>
        /// This program hosts a Web API that has a controller decorated with a PerfIt filter and then
        /// sends an HTTP request to instrument.
        /// Since it is net452, it will raise ETW that can be captured by Enterprise Library. Note listener.LogToConsole();
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            string baseAddress   = "http://localhost:34543/";
            var    configuration = new HttpSelfHostConfiguration(baseAddress);

            configuration.Routes.Add("def", new HttpRoute("api/{controller}"));
            var server = new HttpSelfHostServer(configuration);

            server.OpenAsync().Wait();

            var listener = new ObservableEventListener();

            listener.EnableEvents(InstrumentationEventSource.Instance, EventLevel.LogAlways,
                                  Keywords.All);

            listener.LogToConsole();

            var client = new HttpClient();
            var result = client.GetAsync(baseAddress + "api/test").Result;

            Console.WriteLine(result.Content.ReadAsStringAsync().Result);

            result.EnsureSuccessStatusCode();
            server.CloseAsync().Wait();

            Console.Read();
        }
Example #24
0
 public void CleanupHost()
 {
     if (server != null)
     {
         server.CloseAsync().Wait();
     }
 }
        static void Main(string[] args)
        {
            // Set up server configuration
            Uri _baseAddress = new Uri("http://localhost:60064/");
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);

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

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

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

            // Connect mqtt client
            clsMQTTClient.Instance.ConnectMqttClient();


            Console.WriteLine("PCShop Web-API Self hosted on " + _baseAddress +
                              _TextArt);
            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
            server.CloseAsync().Wait();

            // Disconnect mqtt client
            clsMQTTClient.Instance.DisconnectMqttClient();
        }
Example #26
0
        protected override void OnStart(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:9011");

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

            server = new HttpSelfHostServer(config);

            server.OpenAsync().Wait();

            try
            {
                //Só para verificar servidor de banco de dados
                ProductController   productController   = new ProductController();
                ComponentController componentController = new ComponentController();
                //Só para verificar servidor de banco de dados - Fim
            }
            catch (Exception ex)
            {
                server.CloseAsync();
            }
        }
Example #27
0
 public void Dispose()
 {
     if (_server != null)
     {
         _server.CloseAsync().Wait();
     }
 }
Example #28
0
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            config.Routes.MapHttpRoute("API", "{controller}/{action}/{id}",
                                       new { id = RouteParameter.Optional });
            //設定Self-Host Server,由於會使用到網路資源,用using確保會Dispose()加以釋放
            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                using (var httpServer = new HttpSelfHostServer(config))
                {
                    //OpenAsync()屬非同步呼叫,加上Wait()則等待開啟完成才往下執行
                    httpServer.OpenAsync().Wait();
                    Console.WriteLine("Web API host started...");
                    //輸入exit按Enter結束httpServer
                    string line = null;
                    do
                    {
                        line = Console.ReadLine();
                    }while (line != "exit");
                    //結束連線
                    httpServer.CloseAsync().Wait();
                }
            }
        }
Example #29
0
        static void Main(string[] args)
        {
            Console.WriteLine(typeof(int).BaseType.BaseType);

            HttpSelfHostServer server = null;

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

                // Generate a model
                IEdmModel model = GetEdmModel();

                // Create the OData formatter and give it the model
                ODataMediaTypeFormatter odataFormatter = new ODataMediaTypeFormatter(model);
                configuration.Formatters.Clear();
                configuration.SetODataFormatter(odataFormatter);

                // Metadata routes to support $metadata and code generation in the WCF Data Service client.
                configuration.Routes.MapHttpRoute(ODataRouteNames.Metadata, "$metadata", new { Controller = "ODataMetadata", Action = "GetMetadata" });
                configuration.Routes.MapHttpRoute(ODataRouteNames.ServiceDocument, "", new { Controller = "ODataMetadata", Action = "GetServiceDocument" });

                // Relationship routes (notice the parameters is {type}Id not id, this avoids colliding with GetById(id)).
                configuration.Routes.MapHttpRoute(ODataRouteNames.PropertyNavigation, "{controller}({parentId})/{navigationProperty}");

                // Route for manipulating links.
                //configuration.Routes.MapHttpRoute(ODataRouteNames.Link, "{controller}({id})/$links/Products");
                configuration.Routes.MapHttpRoute(ODataRouteNames.Link, "{controller}({id})/$links/{navigationProperty}");

                // Routes for urls both producing and handling urls like ~/Product(1), ~/Products() and ~/Products
                configuration.Routes.MapHttpRoute(ODataRouteNames.GetById, "{controller}({id})");
                configuration.Routes.MapHttpRoute(ODataRouteNames.DefaultWithParentheses, "{controller}()");
                configuration.Routes.MapHttpRoute(ODataRouteNames.Default, "{controller}");

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

                // 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();
                }
            }
        }
Example #30
0
        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();
            }
        }