예제 #1
0
        static void Main()
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8081");

            config.MapHttpAttributeRoutes();


            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();

                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
예제 #2
0
        private void Listen()
        {
            var    ip      = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["HttpIn"].IPEndpoint;
            string address = string.Format("http://{0}:{1}/", ip.Address, ip.Port);
            var    config  = new HttpSelfHostConfiguration(address);


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

            _server = new HttpSelfHostServer(config);

            _server.OpenAsync().Wait();
        }
예제 #3
0
        /// <summary>
        ///
        /// </summary>
        public App()
        {
            //获取本地地址绑定端口
            Uri urlBase = new UriBuilder(ConfigurationManager.AppSettings.Get("InternalUrl") ?? "http://127.0.0.1:8080").Uri;

            _config = new HttpSelfHostConfiguration(urlBase);
            _config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
            _config.TransferMode = TransferMode.Streamed;
            //_config.MaxBufferSize = int.MaxValue;
            //_config.MaxReceivedMessageSize = long.MaxValue;
            //清除xml格式数据 返回json格式
            _config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            //添加全局模型验证
            _config.Filters.Add(new ModelValidationFilterAttribute());
        }
        public void Run()
        {
            var conf = new HttpSelfHostConfiguration(new Uri("http://localhost:18090"));

            WebApiConfiguration.ControllerResolve(conf);
            WebApiConfiguration.Route(conf);
            WebApiConfiguration.UseJsonOnly(conf);
            // WebApiConfiguration.EnableSessionInHttpContext(); // NOTE: got null. need to research.

            using (var server = new HttpSelfHostServer(conf)) {
                server.OpenAsync().Wait();
                Console.WriteLine("Hosted!");
                Console.ReadLine();
            }
        }
        public static void Initialize(TestContext context)
        {
            baseAddress = new Uri("http://localhost:9001");
            config      = new HttpSelfHostConfiguration(baseAddress);

            WebApiConfig.Register(config);

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

            client = new HttpClient
            {
                BaseAddress = baseAddress
            };
        }
예제 #6
0
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8080");

            config.Routes.MapHttpAttributeRoutes(cfg => cfg.AddRoutesFromController <LunchAndLearnController>());
            config.MessageHandlers.Add(new SimpleCorsHandler());

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                Console.WriteLine("Starting Service...");
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
예제 #7
0
        private void StartWebAPI()
        {
            Log.ConsoleAndFile("Starting server...");
            var config = new HttpSelfHostConfiguration(string.Format("http://{0}:{1}/", Config.Settings.BindIP, Config.Settings.Port));

            config.Routes.MapHttpRoute(
                "API Default", Config.Settings.MainEndpointName + "/{controller}/{action}/{id}",
                new { id = RouteParameter.Optional });

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            m_apiServer = new HttpSelfHostServer(config);
            m_apiServer.OpenAsync().Wait();
            Log.ConsoleAndFile(string.Format("Server is running on {0}:{1}/{2}/.", Config.Settings.BindIP, Config.Settings.Port, Config.Settings.MainEndpointName));
        }
예제 #8
0
        public void OnStart(string[] args)
        {
            //string pubIp = new System.Net.WebClient().DownloadString("https://api.ipify.org");
            var config = new HttpSelfHostConfiguration("http://" + /*pubIp*/ "localhost" + ":" + SessionIdentity.Port + "/");

            config.Routes.MapHttpRoute(name: "API",
                                       routeTemplate: "{controller}/{action}/{id}",
                                       defaults: new { id = RouteParameter.Optional });
            _server   = new HttpSelfHostServer(config);
            IsRunning = true;
            config.MaxConcurrentRequests  = 1000;
            config.MaxBufferSize          = 1147483648;
            config.MaxReceivedMessageSize = 1147483648;
            _server.OpenAsync().Wait();
        }
예제 #9
0
         public void Start()
         {
 
             var config = new HttpSelfHostConfiguration(URL);
             config.TransferMode = TransferMode.Streamed;
             
             AddAPIRoute(config);
 
             server = new HttpSelfHostServer(config);
             var task = server.OpenAsync();
             task.Wait();
             //Console.WriteLine("Web API Server has started at:" + URL);
             //Console.ReadLine();
 
         }
예제 #10
0
        static void Main(string[] args)
        {
            var selfHostConfiguraiton = new HttpSelfHostConfiguration("http://localhost:5555");

            selfHostConfiguraiton.Routes.MapHttpRoute(
                name: "DefaultApiRoute",
                routeTemplate: "{controller}/{action}/{id}",
                defaults: null
                );
            using (var server = new HttpSelfHostServer(selfHostConfiguraiton))
            {
                server.OpenAsync().Wait();
                Console.ReadLine();
            }
        }
예제 #11
0
        public async Task GetReturnsSuccessStatusCode()
        {
            string baseAddress = "https://localhost:5001";
            HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration(baseAddress);
            HttpSelfHostServer        server        = new HttpSelfHostServer(configuration);

            using HttpClient client = new HttpClient(server);

            HttpResponseMessage response = await client.GetAsync("paths");

            Assert.That(
                response.IsSuccessStatusCode,
                Is.True
                );
        }
예제 #12
0
        static void Main(string[] args)
        {
            Trace.Listeners.Add(new ConsoleTraceListener());
            var config = new HttpSelfHostConfiguration("http://localhost:8080")
            {
                TransferMode = TransferMode.Streamed
            };
            var server = new HttpSelfHostServer(config, new ProxyMessageHandler());

            server.OpenAsync().Wait();
            Trace.TraceInformation("server is opened");
            Console.ReadKey();
            server.CloseAsync().Wait();
            Trace.TraceInformation("server is closed, bye");
        }
예제 #13
0
        protected override void OnStart(string[] args)
        {
            var httpAddress = System.Configuration.ConfigurationManager.AppSettings["APIUrl"];
            var httpconfig  = new HttpSelfHostConfiguration(httpAddress);

            httpconfig.MessageHandlers.Add(new CorsHandler());

            httpconfig.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
            httpServer = new HttpSelfHostServer(httpconfig);
            httpServer.OpenAsync().Wait();
        }
예제 #14
0
        public static async Task <Tuple <HttpSelfHostServer, Service.Config.Config> > InitService(Uri url, Service.Config.Config config = null)
        {
            var cfg = new HttpSelfHostConfiguration(url)
            {
                IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always,
                HostNameComparisonMode   = HostNameComparisonMode.Exact
            };

            config = Application.InitApp(cfg, config);
            config.UpdateLifeTime = TimeSpan.FromDays(1);
            var server = new HttpSelfHostServer(cfg);
            await server.OpenAsync();

            return(Tuple.Create(server, config));
        }
예제 #15
0
        public ServerStartup()
        {
            var config = new HttpSelfHostConfiguration($"http://{ConfigurationService.Instance.Get<string>(Constants.ServerHost)}:{ConfigurationService.Instance.Get<string>(Constants.ServerPort)}");

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

            _server = new HttpSelfHostServer(config);

            _metricReporter = new TimedReporter <MetricResult>(new InMemoryRepository <MetricResult>(), new ElasticRestRepository <MetricResult>(new InMemoryRepository <MetricResult>()));

            _retentionPolicyMetrics = new TimedElasticSearchRetentionPolicy <MetricResult>();
        }
예제 #16
0
        public virtual void Setup()
        {
            BaseUri = new Uri("http://localhost:58193");
            var config = new HttpSelfHostConfiguration(BaseUri);

            ContainerBuilder = ContainerBuilder ?? new ContainerBuilder();
            ContainerBuilder.RegisterApiControllers(typeof(HomeController).Assembly);
            Container = ContainerBuilder.Build();

            //RouteConfig.RegisterRoutes(config);
            config.DependencyResolver = new AutofacWebApiDependencyResolver(Container);

            _webServer = new HttpSelfHostServer(config);
            _webServer.OpenAsync().Wait();
        }
        public static HttpSelfHostConfiguration ConfigureSite(string baseAddress)
        {
            var config = new HttpSelfHostConfiguration(baseAddress);

            config.Formatters.Add(new ViewEngineFormatter(new RazorViewEngine()));
            config.Formatters.Add(new PlainTextFormatter());

            config.MessageHandlers.Add(new W3CLogger("web.log"));

            config.Routes.MapHttpRoute("css", "css/{name}", new { controller = "Stylesheets" });
            config.Routes.MapHttpRoute("js", "js/{name}", new { controller = "Javascript" });
            config.Routes.MapHttpRoute("default", "{controller}", new { controller = "Home" });

            return(config);
        }
예제 #18
0
        /// <summary>
        /// Self Host
        /// </summary>
        /// <param name="authUrl"></param>
        private static void SelfHostWebApi(string authUrl)
        {
            var config = new HttpSelfHostConfiguration(authUrl);

            Startup.Configure(config);

            var server = new HttpSelfHostServer(config);
            var task   = server.OpenAsync();

            task.Wait();

            Console.WriteLine("Web API Server has started at {0}.", authUrl);
            Console.WriteLine("Hit Enter to shutdown Web API Server.");
            Console.ReadLine();
        }
예제 #19
0
        private static HttpSelfHostConfiguration GetHostConfig(int portNumber)
        {
            var baseAddress = string.Format("http://{0}:{1}",
                                            Constants.WebHost.HostName, portNumber);
            var config = new HttpSelfHostConfiguration(baseAddress);

            config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{id}",
                new
            {
                id = RouteParameter.Optional
            });
            return(config);
        }
예제 #20
0
        private static void OutputApiDiscoveryDetail(HttpSelfHostConfiguration config, string baseAddress)
        {
            IApiExplorer apiExplorer = config.Services.GetApiExplorer();

            foreach (ApiDescription api in apiExplorer.ApiDescriptions)
            {
                Console.WriteLine("URI: {0}/{1}", baseAddress, api.RelativePath);
                Console.WriteLine("HTTP method: {0}", api.HttpMethod);
                foreach (ApiParameterDescription parameter in api.ParameterDescriptions)
                {
                    Console.WriteLine("Parameter: {0} - {1}", parameter.Name, parameter.Source);
                }
                Console.WriteLine();
            }
        }
예제 #21
0
        static void Main()
        {
            var config = new HttpSelfHostConfiguration(new Uri("http://localhost:9200"));

            ServiceConfiguration.Configure(config);

            var host = new HttpSelfHostServer(config);

            host.OpenAsync().Wait();

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();

            host.CloseAsync().Wait();
        }
예제 #22
0
        public static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration(new Uri(@"http://127.0.0.1:7777"));

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

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("3DWebApi Server is Running...");
                Console.ReadLine();
            }
        }
예제 #23
0
        /// <summary>
        /// 开启WebApi监听服务
        /// </summary>
        public static void Start()
        {
            string baseAddress = "http://localhost:8080";

            Console.WriteLine(baseAddress);
            var config = new HttpSelfHostConfiguration(baseAddress); //配置主机

            config.Routes.MapHttpRoute(
                name: "API Default",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional });
            server = new HttpSelfHostServer(config); //监听HTTP
            server.OpenAsync().Wait();               //开启来自客户端的请求
            Console.WriteLine("开启Http监听");
        }
예제 #24
0
        static void Main(string[] args)
        {
            Assembly.Load("WebApi,Version=1.0.0.0,Culture=neutral");
            //Assembly.LoadFile(@"F:\git\TestWebApi\WebApi\WebApi\WebApi\bin\WebApi.dll");
            HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration("http://localhost/selfhost");

            using (HttpSelfHostServer httpServer = new HttpSelfHostServer(configuration))
            {
                httpServer.Configuration.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional });

                httpServer.OpenAsync();

                Console.Read();
            }
        }
예제 #25
0
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8089");

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

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");
                Console.ReadLine();
            }
        }
예제 #26
0
 public static void App_Configure(HttpSelfHostConfiguration config)
 {
     config.Routes.MapHttpRoute(
         "DefaultApi",
         "api/{controller}/{id}",
         defaults: new { id = RouteParameter.Optional }
         );
     //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
     config.Formatters.JsonFormatter.Indent = true;
     config.Formatters.JsonFormatter.SerializerSettings.Formatting            = Newtonsoft.Json.Formatting.Indented;
     config.Formatters.JsonFormatter.SerializerSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
     config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling     = Newtonsoft.Json.NullValueHandling.Ignore;
     config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
     config.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling  = Newtonsoft.Json.DefaultValueHandling.Ignore;
 }
예제 #27
0
        static void Main(string[] args)
        {
            /*In the above code, first we created an object of HttpSelfHostConfiguration class by passing uri location. Then, we created an object of HttpSelfHostServer by passing config and HttpMessageHandler object. And then we started listening for incoming request by calling server.OpenAsync() method. This will listen requests asynchronously, so it will return Task object.*/
            //need using System.Web.Http.SelfHost; aft downloading from NuGet & adding ref

            var config = new HttpSelfHostConfiguration("http://localhost:1234");

            var server = new HttpSelfHostServer(config, new MyWebAPIMessageHandler());//create a server, pass configuration obj & an API obj
            var task   = server.OpenAsync();

            task.Wait();

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

            config.MaxBufferSize          = 1000000;
            config.MaxReceivedMessageSize = 1000000;

            var server = new HttpSelfHostServer(config, new MyWebAPIMessageHandler());
            var task   = server.OpenAsync();

            task.Wait();

            Console.WriteLine("Web API Server has started at http://localhost:1234");
            Console.ReadLine();
        }
        public void Start()
        {
            var port = ConfigurationManager.AppSettings["ServicePort"];

            var config = new HttpSelfHostConfiguration("http://localhost:" + port);

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

            server.OpenAsync().Wait();
        }
예제 #30
0
        static void Main(string[] args)
        {
            HttpSelfHostServer server = null;

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

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

                // Set up ResponseEntityHandler with a temporary folder
                Directory.CreateDirectory(TempFolder);
                DelegatingHandler responseEntityHandler = new ResponseEntityHandler(TempFolder);

                // Add our sample message handler to the server configuration
                config.MessageHandlers.Add(responseEntityHandler);

                server = new HttpSelfHostServer(config);
                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();
                }
            }
        }