Example #1
0
        private void StartApiHost()
        {
            var configuration = new HttpSelfHostConfiguration($"http://0.0.0.0:{_port}");

            configuration.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
            configuration.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
            configuration.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
            configuration.Routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
            configuration.Services.Replace(typeof(IAssembliesResolver), new CustomAssemblyResolver());
            configuration.DependencyResolver     = ContainerBuilder.GetContainer();
            configuration.MaxReceivedMessageSize = _maxMessageSize;
#if DEBUG
            configuration.Services.Replace(typeof(IExceptionHandler), new DebuggingExceptionHandler());
#endif
            _httpSelfHostServer = new HttpSelfHostServer(configuration);
            _httpSelfHostServer.OpenAsync().Wait();
        }
Example #2
0
        static void Main(string[] args)
        {
            var serviceHostConfig = new HttpSelfHostConfiguration("https://127.0.0.1:34343");

            //serviceHostConfig.ClientCredentialType = HttpClientCredentialType.Certificate;
            serviceHostConfig.ClientCredentialType = HttpClientCredentialType.None;

            serviceHostConfig.MessageHandlers.Add(new TestAuthorizationMetadataHandler());

            var server = new HttpSelfHostServer(serviceHostConfig);

            server.OpenAsync().Wait();

            Console.WriteLine("Press Enter to exit..");
            GC.KeepAlive(server);
            Console.ReadLine();
        }
Example #3
0
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration(new Uri("http://localhost:6635"));

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

                );
            var host = new HttpSelfHostServer(config);

            host.OpenAsync().Wait();
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
            host.CloseAsync().Wait();
        }
Example #4
0
        public void Run()
        {
            var    configuration         = new HttpSelfHostConfiguration(Endpoint);
            object defaultControllerName = "Depth";

            configuration.Routes.MapHttpRoute("API Default", "{action}", new { controller = defaultControllerName });

            using (var server = new HttpSelfHostServer(configuration))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Server running...");

                Thread.Sleep(new TimeSpan(0, 10, 0));

                server.CloseAsync().Wait();
            }
        }
Example #5
0
        public void Start()
        {
            var nodeConfigString = File.ReadAllText("config.json");
            var settings         = new Newtonsoft.Json.JsonSerializerSettings
            {
                TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto,
            };
            var config = Newtonsoft.Json.JsonConvert.DeserializeObject <JSONConfig>(nodeConfigString, settings);

            // config Syslog listener
            if (config.syslog.listenerEnabled)
            {
                var          listener      = new SyslogListener();
                Action <int> startListener = listener.Start;
                startListener.BeginInvoke(config.syslog.listenerPort, null, null);
            }

            // config PollEngine
            foreach (var node in (config.nodes ?? new JSONConfigNode[0]))
            {
                var pollNode = Activator.CreateInstance(typeof(PollingEngine).Assembly.GetType(node.type), new object[] { node.name, node.groups ?? new string[0], node.settings }) as PollNode;
                PollingEngine.TryAdd(pollNode);
            }
            PollingEngine.StartPolling();

            // config HTTP API
            var hostConfig = new HttpSelfHostConfiguration("http://127.0.0.1:" + config.http.listenerPort);

            // Remove the XML formatter
            hostConfig.Formatters.Remove(hostConfig.Formatters.XmlFormatter);
            hostConfig.Formatters.Add(new RazorFormatter());
            hostConfig.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
            hostConfig.Formatters.JsonFormatter.SerializerSettings.Formatting       = Newtonsoft.Json.Formatting.Indented;
            hostConfig.Formatters.JsonFormatter.SerializerSettings.Error           += (x, y) =>
            {
                return;
            };
            hostConfig.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
            // Attribute routing.
            hostConfig.MapHttpAttributeRoutes();
            hostConfig.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            hostConfig.Filters.Add(new ApiExceptionFilterAttribute());

            httpServer = new HttpSelfHostServer(hostConfig);
            httpServer.OpenAsync().Wait();
        }
Example #6
0
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:12345");

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

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to Exit");
                Console.ReadLine();
            }
        }
Example #7
0
        public WebApiHost()
        {
            string webApiPort = ConfigurationManager.AppSettings["WebApiPort"];

            _baseAddress = $"http://0.0.0.0:{webApiPort}/";
            var config = new HttpSelfHostConfiguration(_baseAddress);

            config.MessageHandlers.Add(new DecompressionHandler());
            config.MaxReceivedMessageSize = 64 * 1024 * 1024;
            loadControllerDlls(config.Routes);
            config.Routes.MapHttpRoute("API Default", "api/{controller}/{action}", new { action = RouteParameter.Optional });

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

            _log.InfoFormat("WebApi 服务 {0} 开始工作。", _baseAddress);
        }
Example #8
0
        static void Main(string[] args)
        {
            var  config = new HttpSelfHostConfiguration("http://localhost:8080");
            bool isolateAreaSwaggers;

            bool.TryParse(ConfigurationManager.AppSettings["isolateAreaSwaggers"], out isolateAreaSwaggers);

            SwaggerConfig.Register(config, isolateAreaSwaggers);
            WebApiConfig.Register(config);

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
Example #9
0
    static void Main(string[] args)
    {
        HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration(baseAddress);

        configuration.Routes.MapHttpRoute("default", "api/{controller}");
        HttpSelfHostServer server = new HttpSelfHostServer(configuration);

        try
        {
            server.OpenAsync().Wait();
            RunClient();
        }
        finally
        {
            server.CloseAsync().Wait();
        }
    }
Example #10
0
        public ApiServer()
        {
            const string machineName = "localhost";

            HostUrl = string.Format("http://{0}:{1}/", machineName, Port);

            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(HostUrl);

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

            _server = new HttpSelfHostServer(config);
            _server.OpenAsync().Wait(TimeSpan.FromSeconds(20));
        }
Example #11
0
        static void Main(string[] args)
        {
            //Assembly.Load("CM.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");    //加载外部程序集
            var config = new HttpSelfHostConfiguration("http://localhost:8083");

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });
            //config.Services.Replace(typeof(IAssembliesResolver), new UserResolver());
            config.Services.Replace(typeof(IAssembliesResolver), new WebApiResolver());
            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            config.Routes.MapHttpRoute(
                "ApiDefault",
                "api/{controller}/{id}",
                new { id = RouteParameter.Optional }
                );

            var server = new HttpSelfHostServer(config);

            server.OpenAsync().Wait();
            Console.WriteLine("Server is opened");
            Console.ReadKey();
            server.CloseAsync().Wait();
        }
Example #13
0
 public static bool StartWebApiService()
 {
     try
     {
         var uri = new Uri(@"http://localhost:80/HHCloud/");
         HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(uri);
         WebApiConfig.Config(config);
         var host = new HttpSelfHostServer(config);
         host.OpenAsync().Wait();
         return(true);
     }
     catch (Exception ex)
     {
         LJH.GeneralLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex);
     }
     return(false);
 }
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:58710/");

            config.Routes.MapHttpRoute("default",
                                       "api/{controller}/{id}",
                                       new { controller = "Home", id = RouteParameter.Optional });

            var server = new HttpSelfHostServer(config);

            var task = server.OpenAsync();

            task.Wait();

            Console.WriteLine("Web API Server has started at http://localhost:58710");
            Console.ReadLine();
        }
    static void Main(string[] args)
    {
        var config = new HttpSelfHostConfiguration("http://localhost:8080");

        config.Routes.MapHttpRoute(
            name: "DefaultApiRoute",
            routeTemplate: "{controller}/{id}.{format}",
            defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional },
            constraints: null
            );
        using (var server = new HttpSelfHostServer(config))
        {
            server.OpenAsync().Wait();
            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
        }
    }
        static void Main(string[] args)
        {
            //var configuration = new HttpSelfHostConfiguration("http://localhost:8086");

            var configuration = new MySelfHostConfiguration("https://localhost:8086");

            WebApiConfig.Register(configuration);
            DtoMapperConfig.CreateMaps();
            IocConfig.RegisterDependencyResolver(configuration);

            using (HttpSelfHostServer server = new HttpSelfHostServer(configuration))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to terminate the server...");
                Console.ReadLine();
            }
        }
        public override async Task RunAsync()
        {
            Utilities.PrintLogo();

            var scriptPath = ScriptHostHelpers.GetFunctionAppRootDirectory(Environment.CurrentDirectory);
            var traceLevel = await ScriptHostHelpers.GetTraceLevel(scriptPath);

            var settings = SelfHostWebHostSettingsFactory.Create(traceLevel, scriptPath);

            await ReadSecrets(scriptPath);

            var baseAddress = Setup();

            var config = new HttpSelfHostConfiguration(baseAddress)
            {
                IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always,
                TransferMode             = TransferMode.Streamed,
                HostNameComparisonMode   = HostNameComparisonMode.Exact,
                MaxReceivedMessageSize   = 1 * 1024 * 1024 * 100 // 1 byte * 1,024 * 1,024 * 100 = 100 MB (or 104,857,600 bytes)
            };

            if (!string.IsNullOrEmpty(CorsOrigins))
            {
                var cors = new EnableCorsAttribute(CorsOrigins, "*", "*");
                config.EnableCors(cors);
            }
            config.Formatters.Add(new JsonMediaTypeFormatter());

            Environment.SetEnvironmentVariable("EDGE_NODE_PARAMS", $"--debug={NodeDebugPort}", EnvironmentVariableTarget.Process);

            WebApiConfig.Initialize(config, settings: settings);

            using (var httpServer = new HttpSelfHostServer(config))
            {
                await httpServer.OpenAsync();

                ColoredConsole.WriteLine($"Listening on {baseAddress}");
                ColoredConsole.WriteLine("Hit CTRL-C to exit...");
                await PostHostStartActions(config);

                await Task.Delay(-1);

                await httpServer.CloseAsync();
            }
        }
        static void Main(string[] args)
        {
            HttpSelfHostServer server = null;

            try
            {
                // Set up server configuration
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
                config.HostNameComparisonMode = HostNameComparisonMode.Exact;
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                    );
                // Set our own assembly resolver where we add the assemblies we need
                DynamicAssemblyResolver assemblyResolver = new DynamicAssemblyResolver();
                config.Services.Replace(typeof(IAssembliesResolver), assemblyResolver);
                // Create server
                server = new HttpSelfHostServer(config);
                // Start listening
                server.OpenAsync().Wait();
                Console.WriteLine("Listening on " + _baseAddress);
                while (true)
                {
                    // Run HttpClient issuing requests
                    RunDynamicClientAsync();
                    Console.WriteLine("Press Ctrl+C 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)
                {
                    // Stop listening
                    server.CloseAsync().Wait();
                }
            }
        }
        static void Main(string[] args)
        {
            HttpSelfHostServer server = null;

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

                // Register default route
                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);

                // Run HttpClient issuing requests
                RunClient();

                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)
                {
                    // Stop listening
                    server.CloseAsync().Wait();
                }
            }
        }
Example #20
0
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.ApplicationExit += Token.ApplicationExit;
            Application.SetCompatibleTextRenderingDefault(false);
            MefBootstrapper.ComposeParts();
            var creationService = new DataCreationService();

            creationService.CreateData();

            var apiHost  = LocalSettings.ApiHost;
            var apiPort  = LocalSettings.ApiPort;
            var httpHost = string.Format("http://{0}:{1}", apiHost, apiPort);

            var config = new HttpSelfHostConfiguration(httpHost);

            //GET =>  http://localhost:8080/api/getToken/{pin}
            config.Routes.MapHttpRoute("LoginRoute", "api/getToken/{pin}", new
            {
                controller = "Login"
            });
            //GET =>  http://localhost:8080/api/{token}/{controller}/{id}
            config.Routes.MapHttpRoute("API Default", "api/{token}/{controller}/{id}",
                                       new
            {
                id = RouteParameter.Optional
            });

            using (var server = new HttpSelfHostServer(config))
            {
                server.Configuration.DependencyResolver = new MefDependencyResolver(MefBootstrapper.Container);
                server.OpenAsync().Wait();

                if (LocalSettings.TokenLifeTime.Ticks > 0)
                {
                    var tokenGarbageTimer = new Timer
                    {
                        Interval = (int)new TimeSpan(0, 1, 0).TotalMilliseconds
                    };
                    tokenGarbageTimer.Tick += Token.CollectGarbage;
                    tokenGarbageTimer.Start();
                }
                Application.Run(new FrmMain());
            }
        }
Example #21
0
        static void Main(string[] args)
        {
            const string host   = "http://localhost:8085";
            var          config = new HttpSelfHostConfiguration(host);

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

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine(string.Format("Listing on {0} ...", host));
                Console.WriteLine("WebAPI Server is up an running");
                Console.ReadLine();
            }
        }
Example #22
0
        private void startAtPort(string rootDirectory, FubuRuntime runtime)
        {
            _baseAddress   = "http://localhost:" + _port;
            _configuration = new HttpSelfHostConfiguration(_baseAddress);

            FubuMvcPackageFacility.PhysicalRootPath = rootDirectory;

            _server = new HttpSelfHostServer(_configuration, new SelfHostHttpMessageHandler(runtime)
            {
                Verbose = Verbose
            });

            runtime.Facility.Register(typeof(HttpSelfHostConfiguration), ObjectDef.ForValue(_configuration));

            Console.WriteLine("Starting to listen for requests at " + _configuration.BaseAddress);

            _server.OpenAsync().Wait();
        }
Example #23
0
        public async Task StartAPI()
        {
            bool apiStatus = false;

            if (apiStatus)
            {
                Console.WriteLine("Starting API");
                var config = new HttpSelfHostConfiguration("http://localhost:8080");

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

                using (HttpSelfHostServer server = new HttpSelfHostServer(config))
                {
                    server.OpenAsync().Wait();
                    Console.WriteLine("API Started");
                }
            }
        }
Example #24
0
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            config.Formatters.JsonFormatter.SupportedMediaTypes
            .Add(new MediaTypeHeaderValue("text/html"));
            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{action}/{id}",
                new { id = RouteParameter.Optional });
            config.MessageHandlers.Add(new CustomHeaderHandler());

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
Example #25
0
        public static HttpSelfHostConfiguration HostWebAPI()
        {
            if (configuration == null)
            {
                Assembly.Load("IntegratedManagement.MiddleBaseAPI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
                configuration = new HttpSelfHostConfiguration(baseHttpAddr);
                using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration))
                {
                    httpServer.Configuration.Routes.MapHttpRoute(
                        name: "DefaultApi",
                        routeTemplate: "api/{controller}/{id}",
                        defaults: new { id = RouteParameter.Optional });

                    httpServer.OpenAsync();
                }
            }
            return(configuration);
        }
Example #26
0
        static void Main(string[] args)
        {
            var selfHostConfiguraiton = new HttpSelfHostConfiguration(HOST);

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

            using (var server = new HttpSelfHostServer(selfHostConfiguraiton))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Started...");

                Console.ReadKey();
            }
        }
Example #27
0
 internal static void RunServer(string endpoint)
 {
     Task.Run(
         async() =>
     {
         while (true)
         {
             var config = new HttpSelfHostConfiguration(endpoint);
             config.Routes.MapHttpRoute(
                 "API Default",
                 "api/{controller}/{action}");
             var server = new HttpSelfHostServer(config);
             await server.OpenAsync();
             await Task.Delay(TimeSpan.MaxValue);
             server.Dispose();
         }
     });
 }
Example #28
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var baseAddress = ConfigurationManager.AppSettings["baseAddress"];
            var config      = new HttpSelfHostConfiguration(baseAddress);

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
            var cors = new EnableCorsAttribute("*", "*", "*");

            config.EnableCors(cors);
            var server = new HttpSelfHostServer(config);

            server.OpenAsync().Wait();
        }
Example #29
0
        public static void Start(int intPort)
        {
            HttpSelfHostConfiguration _config = new HttpSelfHostConfiguration("http://localhost:" + intPort);

            _config.MaxReceivedMessageSize = int.MaxValue;
            _config.MaxBufferSize          = int.MaxValue;
            _config.Formatters.Clear();
            _config.Formatters.Add(new JsonMediaTypeFormatter());
            _config.Routes.MapHttpRoute(
                name: "DefaultApinew",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            //start
            m_serverhost = new HttpSelfHostServer(_config);
            m_serverhost.OpenAsync().Wait();
        }
        private static void Main(string[] args)
        {
            string baseAddress = "http://localhost:8080";
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);

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

            // Configure help page
            HelpPageConfig.Register(config);

            HttpSelfHostServer server = new HttpSelfHostServer(config);

            server.OpenAsync().Wait();
            Console.WriteLine("Service listening at: {0}", baseAddress);
            Console.WriteLine("Help page available at: {0}/help", baseAddress);
            Console.WriteLine("Press Enter to shutdown the service.");
            Console.ReadLine();
        }