public IHostingEngine Build()
        {
            var configBuider = new ConfigurationBuilder();

            configBuider.AddInMemoryCollection(new Dictionary<string, string> {{"server.urls", uri}});

            var builder = new WebHostBuilder(configBuider.Build());

            builder.UseStartup(app => { new Startup().ConfigureApplication(app); }, services => { new ServiceConfigurer(documentStore).ConfigureServices(services); });
            builder.UseServer("Microsoft.AspNet.Server.Kestrel");

            return builder.Build();
        }
Пример #2
0
        protected override void OnStart(string[] args)
        {
            try
            {
                var configProvider = new MemoryConfigurationProvider();
                configProvider.Add("server.urls", "http://localhost:5000");

                var config = new ConfigurationBuilder()
                    .Add(configProvider)
                    .Build();

                var builder = new WebHostBuilder(config);
                builder.UseServer("Microsoft.AspNet.Server.Kestrel");
                builder.UseServices(services => services.AddMvc());
                builder.UseStartup(appBuilder =>
                {
                    appBuilder.UseDefaultFiles();
                    appBuilder.UseStaticFiles();
                    appBuilder.UseMvc();
                });

                var hostingEngine = builder.Build();
                _application = hostingEngine.Start();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("error in OnStart: " + ex);
                throw;
            }
        }
 protected override void OnStart(string[] args)
 {
     Log("WWWService started.");           
     try
     {                                       
         var builder = new WebHostBuilder(Configuration);                                                                                                
         builder.UseServer("Microsoft.AspNet.Server.WebListener");                
         builder.UseStartup<Program>();                                                
         var appBuilder = builder.Build();                                                                                       
         appBuilder.Start();
     }
     catch(Exception x)
     {
         Log("WWWService Exception: "+x.Message);
         if (x.InnerException != null)
             Log("WWWService Exception: "+x.InnerException.Message);    
             
         if (x is System.Reflection.ReflectionTypeLoadException)
         {
             var typeLoadException = x as ReflectionTypeLoadException;
             var loaderExceptions  = typeLoadException.LoaderExceptions;
             foreach (var l in loaderExceptions)
             {
                 Log("WWWService TypeLoadException: "+l.Message);                            
             }
         }            
     }
     
 }
Пример #4
0
        protected override void OnStart(string[] args)
        {
            var config = new ConfigurationBuilder()
                                    .SetBasePath(_applicationEnvironment.ApplicationBasePath)
                                    .AddJsonFile($@"{_applicationEnvironment.ApplicationBasePath}\config.json")
                                    .AddEnvironmentVariables()
                                    .Build();

            var builder = new WebHostBuilder(config);
            builder.UseServer("Microsoft.AspNet.Server.WebListener");
            builder.UseServices(services => services.AddMvc());
            builder.UseStartup(appBuilder =>
            {
                appBuilder.UseDefaultFiles();
                appBuilder.UseStaticFiles();
                appBuilder.UseMvc(routes =>
                {
                    routes.MapRoute(
                        null,
                        "{controller}/{action}",
                        new { controller = "Home", action = "Index" });
                });
            });

            _hostingEngine = builder.Build();
            _shutdownServerDisposable = _hostingEngine.Start();
        }
        protected override void OnStart(string[] args)
        {
            try
            {
                var temp = new ConfigurationBuilder()
                    .AddJsonFile("config.json")
                    .AddJsonFile("hosting.json", true)
                    .Build();

                var configProvider = new MemoryConfigurationProvider();
                configProvider.Add("server.urls", temp["WebServerAddress"]);
                configProvider.Add("webroot", temp.Get<string>("webroot", "wwwroot"));

                var config = new ConfigurationBuilder()
                    .Add(configProvider)
                    .Build();

                var builder = new WebHostBuilder(config);
                builder.UseServer("Microsoft.AspNet.Server.Kestrel");
                builder.UseStartup<Startup>();
                
                var hostingEngine = builder.Build();
                _application = hostingEngine.Start();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("error in OnStart: " + ex);
                throw;
            }
        }
        public async Task RegisterAddresses_Success(string addressInput, string[] testUrls)
        {
            var config = new ConfigurationBuilder()
                .AddInMemoryCollection(new Dictionary<string, string>
                {
                    { "server.urls", addressInput }
                })
                .Build();

            var hostBuilder = new WebHostBuilder(config);
            hostBuilder.UseServer("Microsoft.AspNet.Server.Kestrel");
            hostBuilder.UseStartup(ConfigureEchoAddress);            

            using (var app = hostBuilder.Build().Start())
            {
                using (var client = new HttpClient())
                {
                    foreach (var testUrl in testUrls)
                    {
                        var responseText = await client.GetStringAsync(testUrl);
                        Assert.Equal(testUrl, responseText);
                    }
                }
            }
        }
        public async Task LargeDownload()
        {
            var config = new ConfigurationBuilder()
                .AddInMemoryCollection(new Dictionary<string, string>
                {
                    { "server.urls", "http://localhost:8792/" }
                })
                .Build();

            var hostBuilder = new WebHostBuilder(config);
            hostBuilder.UseServer("Microsoft.AspNet.Server.Kestrel");
            hostBuilder.UseStartup(app =>
            {
                app.Run(async context =>
                {
                    var bytes = new byte[1024];
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        bytes[i] = (byte)i;
                    }

                    context.Response.ContentLength = bytes.Length * 1024;

                    for (int i = 0; i < 1024; i++)
                    {
                        await context.Response.Body.WriteAsync(bytes, 0, bytes.Length);
                    }
                });
            });            

            using (var app = hostBuilder.Build().Start())
            {
                using (var client = new HttpClient())
                {
                    var response = await client.GetAsync("http://localhost:8792/");
                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStreamAsync();

                    // Read the full response body
                    var total = 0;
                    var bytes = new byte[1024];
                    var count = await responseBody.ReadAsync(bytes, 0, bytes.Length);
                    while (count > 0)
                    {
                        for (int i = 0; i < count; i++)
                        {
                            Assert.Equal(total % 256, bytes[i]);
                            total++;
                        }
                        count = await responseBody.ReadAsync(bytes, 0, bytes.Length);
                    }
                }
            }
        }
Пример #8
0
        protected virtual DbContext TryCreateContextFromStartup(Type type, string startupAssemblyName)
        {
            var hostBuilder = new WebHostBuilder(_services);
            if (startupAssemblyName != null)
            {
                hostBuilder.UseStartup(startupAssemblyName);
            }

            var appServices = hostBuilder.Build().ApplicationServices;

            return (DbContext)appServices.GetService(type);
        }
Пример #9
0
        public async Task DoWork(CancellationToken ctx)
        {
            var configuration = new ConfigurationBuilder()
                .AddGlobalConfigSources()
                .Build();

            var builder = new WebHostBuilder(configuration.GetSection("Hosting"));
            var engine = builder.Build();

            using (engine.Start())
            {
                await Task.Delay(Timeout.Infinite, ctx);
            }
        }
 public static IServiceProvider CreateServiceProvider(Action<IServiceCollection> configure)
 {
     var host = new WebHostBuilder()
         .UseServer(new ServerFactory())
         .UseStartup(
             _ => { },
             services =>
             {
                 services.AddSignalR();
                 configure(services);
                 return services.BuildServiceProvider();
             });
     return host.Build().ApplicationServices;
 }
Пример #11
0
        public async Task LargeUpload()
        {
            var config = new ConfigurationBuilder()
                .AddInMemoryCollection(new Dictionary<string, string>
                {
                    { "server.urls", "http://localhost:8791/" }
                })
                .Build();

            var hostBuilder = new WebHostBuilder(config);
            hostBuilder.UseServer("Microsoft.AspNet.Server.Kestrel");
            hostBuilder.UseStartup(app =>
            {
                app.Run(async context =>
                {
                    // Read the full request body
                    var total = 0;
                    var bytes = new byte[1024];
                    var count = await context.Request.Body.ReadAsync(bytes, 0, bytes.Length);
                    while (count > 0)
                    {
                        for (int i = 0; i < count; i++)
                        {
                            Assert.Equal(total % 256, bytes[i]);
                            total++;
                        }
                        count = await context.Request.Body.ReadAsync(bytes, 0, bytes.Length);
                    }

                    await context.Response.WriteAsync(total.ToString(CultureInfo.InvariantCulture));
                });
            });            

            using (var app = hostBuilder.Build().Start())
            {
                using (var client = new HttpClient())
                {
                    var bytes = new byte[1024 * 1024];
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        bytes[i] = (byte)i;
                    }
                        
                    var response = await client.PostAsync("http://localhost:8791/", new ByteArrayContent(bytes));
                    response.EnsureSuccessStatusCode();
                    var sizeString = await response.Content.ReadAsStringAsync();
                    Assert.Equal(sizeString, bytes.Length.ToString(CultureInfo.InvariantCulture));
                }
            }
        }
Пример #12
0
        protected override void OnStart(string[] args)
        {
            var builder = new WebHostBuilder(ConfigHandler.Configuration);
            builder.UseServer("Microsoft.AspNet.Server.Kestrel");
            builder.UseServices(services => services.AddMvc());
            builder.UseStartup(appBuilder =>
            {
                appBuilder.UseDefaultFiles();
                appBuilder.UseStaticFiles();
                appBuilder.UseMvc();
            });

            _application = builder.Build().Start();
        }
Пример #13
0
        /// <summary>
        /// Default constructor that AWS Lambda will invoke.
        /// </summary>
        public APIGatewayProxyFunction()
        {
            var builder = new WebHostBuilder();

            Init(builder);

            // Add the API Gateway services in case the override Init method didn't add it. UseApiGateway will
            // not add anything if API Gateway has already been added.
            builder.UseApiGateway();

            _host = builder.Build();
            _host.Start();

            _server = _host.Services.GetService(typeof(Microsoft.AspNetCore.Hosting.Server.IServer)) as APIGatewayServer;
        }
Пример #14
0
        public static void Main(string[] args)
        {
            var hostBuilder = new WebHostBuilder()
                              .UseKestrel()
                              .UseUrls("http://0.0.0.0:5001/")
                              .UseContentRoot(Directory.GetCurrentDirectory())
                              .UseStartup <Startup>();

            Console.WriteLine("urls: {0}", hostBuilder.GetSetting("urls"));

            var host = hostBuilder.Build();


            host.Run();
        }
        public void have_enabled_database_migrations_by_default()
        {
            var webhost = new WebHostBuilder()
                          .UseStartup <DefaultStartup>()
                          .ConfigureServices(services =>
            {
                services.AddHealthChecksUI()
                .AddInMemoryStorage();
            });

            var serviceProvider = webhost.Build().Services;
            var UISettings      = serviceProvider.GetService <IOptions <Settings> >().Value;

            UISettings.DisableMigrations.Should().Be(false);
        }
Пример #16
0
        public void SetUp()
        {
            // Use Kestrel to Host the Controller:
            var builder = new WebHostBuilder()
                          .UseKestrel()
                          .UseStartup <Startup>()
                          .UseUrls("http://localhost:8081")
                          .UseContentRoot(Directory.GetCurrentDirectory());

            // Build the Host:
            this.host = builder.Build();

            // And... Ignite!
            host.Start();
        }
Пример #17
0
        public static void Main(string[] args)
        {
            IWebHostBuilder builder = new WebHostBuilder();

            builder.ConfigureServices(s => {
            });

            builder.UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup <Startup>();

            var host = builder.Build();

            host.Run();
        }
Пример #18
0
        public async Task DoesNotThrowObjectDisposedExceptionFromWriteAsyncAfterConnectionIsAborted()
        {
            var tcs            = new TaskCompletionSource <object>();
            var loggerProvider = new HandshakeErrorLoggerProvider();
            var hostBuilder    = new WebHostBuilder()
                                 .UseKestrel(options =>
            {
                options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions =>
                {
                    listenOptions.UseHttps(TestResources.TestCertificatePath, "testPassword");
                });
            })
                                 .ConfigureLogging(builder => builder.AddProvider(loggerProvider))
                                 .Configure(app => app.Run(async httpContext =>
            {
                httpContext.Abort();
                try
                {
                    await httpContext.Response.WriteAsync($"hello, world");
                    tcs.SetResult(null);
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            }));

            using (var host = hostBuilder.Build())
            {
                host.Start();

                using (var socket = await HttpClientSlim.GetSocket(new Uri($"https://127.0.0.1:{host.GetPort()}/")))
                    using (var stream = new NetworkStream(socket, ownsSocket: false))
                        using (var sslStream = new SslStream(stream, true, (sender, certificate, chain, errors) => true))
                        {
                            await sslStream.AuthenticateAsClientAsync("127.0.0.1", clientCertificates : null,
                                                                      enabledSslProtocols : SslProtocols.Tls11 | SslProtocols.Tls12,
                                                                      checkCertificateRevocation : false);

                            var request = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\nHost:\r\n\r\n");
                            await sslStream.WriteAsync(request, 0, request.Length);

                            await sslStream.ReadAsync(new byte[32], 0, 32);
                        }
            }

            await tcs.Task.TimeoutAfter(TimeSpan.FromSeconds(10));
        }
Пример #19
0
        public static void Main(string[] args)
        {
            Args = args;

            Console.WriteLine();
            Console.WriteLine("ASP.NET Core Benchmarks");
            Console.WriteLine("-----------------------");

            Console.WriteLine($"Current directory: {Directory.GetCurrentDirectory()}");
            Console.WriteLine($"WebHostBuilder loading from: {typeof(WebHostBuilder).GetTypeInfo().Assembly.Location}");

            var config = new ConfigurationBuilder()
                         .AddJsonFile("hosting.json", optional: true)
                         .AddEnvironmentVariables(prefix: "ASPNETCORE_")
                         .AddCommandLine(args)
                         .Build();

            var webHostBuilder = new WebHostBuilder()
                                 .UseContentRoot(Directory.GetCurrentDirectory())
                                 .UseConfiguration(config)
                                 .UseStartup <Startup>()
                                 .ConfigureServices(services => services
                                                    .AddSingleton(new ConsoleArgs(args))
                                                    .AddSingleton <IScenariosConfiguration, ConsoleHostScenariosConfiguration>()
                                                    .AddSingleton <Scenarios>()
                                                    )
                                 .UseDefaultServiceProvider(
                (context, options) => options.ValidateScopes = context.HostingEnvironment.IsDevelopment())
                                 .UseKestrel();

            var threadCount = GetThreadCount(config);

            webHostBuilder.UseSockets(x =>
            {
                if (threadCount > 0)
                {
                    x.IOQueueCount = threadCount;
                }

                Console.WriteLine($"Using Sockets with {x.IOQueueCount} threads");
            });

            var webHost = webHostBuilder.Build();

            Console.WriteLine($"Server GC is currently {(GCSettings.IsServerGC ? "ENABLED" : "DISABLED")}");

            webHost.Run();
        }
Пример #20
0
        public static void Main(string[] args)
        {
            var configurationBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                                       .SetBasePath(Directory.GetCurrentDirectory())
                                       .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                       .AddJsonFile("ocelot.json", true, false)
                                       .AddEnvironmentVariables()
                                       .AddCommandLine(args);

            if (args != null)
            {
                configurationBuilder.AddCommandLine(args);
            }
            var hostingconfig = configurationBuilder.Build();
            var url           = hostingconfig[addressKey] ?? defaultAddress;

            IWebHostBuilder builder = new WebHostBuilder();

            builder.ConfigureServices(s =>
            {
                s.AddSingleton(builder);
            });
            builder.UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseConfiguration(hostingconfig)
            //.ConfigureAppConfiguration((hostingContext, config) =>
            //{
            //    config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
            //    var env = hostingContext.HostingEnvironment;
            //    //config.AddOcelot();
            //    config.AddEnvironmentVariables();
            //})
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                logging.AddConsole();
                logging.AddDebug();
            })
            .UseIISIntegration()
            .UseMetricsWebTracking()
            .UseMetricsEndpoints()
            .UseNLog()
            .UseUrls(url)
            .UseStartup <Startup>();
            var host = builder.Build();

            host.Run();
        }
Пример #21
0
        public void initialize_configuration_using_AddHealthChecksUI_setup_fluent_api()
        {
            var healthCheckName         = "api1";
            var healthCheckUri          = "http://api1/health";
            var webhookName             = "webhook1";
            var webhookUri              = "http://webhook1/sample";
            var webhookPayload          = "payload1";
            var webhookRestorePayload   = "restoredpayload1";
            var evaluationTimeInSeconds = 180;
            var minimumSeconds          = 30;

            var webhost = new WebHostBuilder()
                          .UseStartup <DefaultStartup>()
                          .ConfigureServices(services =>
            {
                services.AddHealthChecksUI(setupSettings: settings =>
                {
                    settings
                    .DisableDatabaseMigrations()
                    .AddHealthCheckEndpoint(name: healthCheckName, uri: healthCheckUri)
                    .AddWebhookNotification(name: webhookName, uri: webhookUri, payload: webhookPayload,
                                            restorePayload: webhookRestorePayload)
                    .SetEvaluationTimeInSeconds(evaluationTimeInSeconds)
                    .SetMinimumSecondsBetweenFailureNotifications(minimumSeconds);
                }).AddInMemoryStorage();
            });

            var serviceProvider = webhost.Build().Services;
            var UISettings      = serviceProvider.GetService <IOptions <Settings> >().Value;

            UISettings.EvaluationTimeInSeconds.Should().Be(evaluationTimeInSeconds);
            UISettings.MinimumSecondsBetweenFailureNotifications.Should().Be(minimumSeconds);

            UISettings.Webhooks.Count.Should().Be(1);
            UISettings.HealthChecks.Count.Should().Be(1);

            var healthcheck = UISettings.HealthChecks[0];

            healthcheck.Name.Should().Be(healthCheckName);
            healthcheck.Uri.Should().Be(healthCheckUri);

            var webhook = UISettings.Webhooks[0];

            webhook.Name.Should().Be(webhookName);
            webhook.Uri.Should().Be(webhookUri);
            webhook.Payload.Should().Be(webhookPayload);
            webhook.RestoredPayload.Should().Be(webhookRestorePayload);
        }
        public void support_combined_configuration_from_fluent_api_and_settings_key()
        {
            var healthCheckName = "api2";
            var healthCheckUri  = "http://api2/healthz";
            var webhookName     = "webhook2";
            var webhookUri      = "http://webhook2";
            var webhookPayload  = "payload1";

            var webhost = new WebHostBuilder()
                          .ConfigureAppConfiguration(conf =>
            {
                conf.Sources.Clear();
                var path = Path.Combine("Functional", "Configuration", "appsettings.json");
                conf.AddJsonFile(path, false);
            }).ConfigureServices(services =>
            {
                services.AddHealthChecksUI(setupSettings: setup =>
                {
                    setup
                    .AddHealthCheckEndpoint(name: healthCheckName, uri: healthCheckUri)
                    .AddWebhookNotification(name: webhookName, uri: webhookUri, payload: webhookPayload)
                    .SetMinimumSecondsBetweenFailureNotifications(200);
                });
            });

            var serviceProvider = webhost.Build().Services;
            var UISettings      = serviceProvider.GetService <IOptions <Settings> >().Value;

            UISettings.MinimumSecondsBetweenFailureNotifications.Should().Be(200);
            UISettings.EvaluationTimeInSeconds.Should().Be(20);
            UISettings.Webhooks.Count.Should().Be(2);
            UISettings.HealthChecks.Count.Should().Be((2));

            var healthCheck1 = UISettings.HealthChecks[0];
            var healthCheck2 = UISettings.HealthChecks[1];
            var webHook1     = UISettings.Webhooks[0];
            var webHook2     = UISettings.Webhooks[1];

            healthCheck1.Name.Should().Be("api1");
            healthCheck1.Uri.Should().Be("http://api1/healthz");
            healthCheck2.Name.Should().Be("api2");
            healthCheck2.Uri.Should().Be("http://api2/healthz");

            webHook1.Name.Should().Be("webhook1");
            webHook1.Uri.Should().Be("http://webhook1");
            webHook2.Name.Should().Be(webhookName);
            webHook2.Uri.Should().Be(webhookUri);
        }
Пример #23
0
        public static IWebHost CreateWebHost()
        {
            var webHostBuilder = new WebHostBuilder()
                                 .UseLoggerFactory(_loggerFactory)
                                 .UseConfiguration(Configuration)
                                 .UseKestrel(options => {
                //options.UseConnectionLogging();
            })
                                 .UseContentRoot(Directory.GetCurrentDirectory())
                                 .UseStartup <Startup>();

            var webHost = webHostBuilder.Build();

            var serverAddresses = webHost.ServerFeatures.Get <IServerAddressesFeature>();

            string pipeName = _startupOptions.WriteServerUrlsToPipe;

            if (pipeName != null)
            {
                NamedPipeClientStream pipe;
                try {
                    pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out);
                    pipe.Connect(10000);
                } catch (IOException ex) {
                    _logger.LogCritical(0, ex, $"Requested to write server.urls to pipe '{pipeName}', but it is not a valid pipe handle.");
                    throw;
                } catch (TimeoutException ex) {
                    _logger.LogCritical(0, ex, $"Requested to write server.urls to pipe '{pipeName}', but timed out while trying to connect to pipe.");
                    throw;
                }

                var applicationLifetime = webHost.Services.GetService <IApplicationLifetime>();
                applicationLifetime.ApplicationStarted.Register(() => Task.Run(() => {
                    using (pipe) {
                        string serverUriStr = JsonConvert.SerializeObject(serverAddresses.Addresses);
                        _logger.LogTrace($"Writing server.urls to pipe '{pipeName}':{Environment.NewLine}{serverUriStr}");

                        var serverUriData = Encoding.UTF8.GetBytes(serverUriStr);
                        pipe.Write(serverUriData, 0, serverUriData.Length);
                        pipe.Flush();
                    }

                    _logger.LogTrace($"Wrote server.urls to pipe '{pipeName}'.");
                }));
            }

            return(webHost);
        }
        public void ItDoesWork()
        {
            var host = new WebHostBuilder()
                       .UseServer(new EmptyServer())
                       .UseStartup <Startup>();

            var services = host.Build().Services;

            Assert.IsType <SqlStore <User> >(services.GetRequiredService <IStore <User> >());
            Assert.IsType <SqlStore <Invoice> >(services.GetRequiredService <IStore <Invoice> >());
            Assert.IsType <SqlStore <Payment> >(services.GetRequiredService <IStore <Payment> >());
            Assert.Throws <ArgumentException>(() =>
            {
                services.GetRequiredService <IStore <int> >();
            });
        }
Пример #25
0
        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddCommandLine(new[] { "--server.urls", "http://localhost:8111" });
            var builder = new WebHostBuilder()
                          .UseConfiguration(config.Build())
                          .UseStartup(typeof(Startup))
                          .UseServer("Microsoft.AspNetCore.Server.Kestrel");

            using (var app = builder.Build())
            {
                app.Start();
                AppLifeTime = (IApplicationLifetime)app.Services.GetService(typeof(IApplicationLifetime));
                AppLifeTime.ApplicationStopping.WaitHandle.WaitOne();
            }
        }
        public void UseCloudHosting_UsesServerPort()
        {
            Environment.SetEnvironmentVariable("SERVER_PORT", "42");
            var hostBuilder = new WebHostBuilder()
                              .UseStartup <TestServerStartup>()
                              .UseKestrel();

            hostBuilder.UseCloudHosting();
            var server = hostBuilder.Build();

            var addresses = server.ServerFeatures.Get <IServerAddressesFeature>();

            Assert.Contains("http://*:42", addresses.Addresses);

            Environment.SetEnvironmentVariable("SERVER_PORT", null);
        }
        public void UseCloudHosting_SeesTyePortsAndUsesAspNetCoreURL()
        {
            Environment.SetEnvironmentVariable("ASPNETCORE_URLS", "http://*:80;https://*:443");
            Environment.SetEnvironmentVariable("PORT", "88;4443");
            var hostBuilder = new WebHostBuilder()
                              .UseStartup <TestServerStartup>()
                              .UseKestrel();

            hostBuilder.UseCloudHosting();
            var server = hostBuilder.Build();

            var addresses = server.ServerFeatures.Get <IServerAddressesFeature>();

            Assert.Contains("http://*:80", addresses.Addresses);
            Assert.Contains("https://*:443", addresses.Addresses);
        }
Пример #28
0
        public async Task TestHelloWorld()
        {
            var builder = new WebHostBuilder().Configure(app => app.UseMvc())
                          .ConfigureServices(svc => svc.AddMvc().AddApplicationPart(Assembly.GetAssembly(typeof(EndToEndApiController))))
                          .UseServer(new CustomListenerHost(new TestListener("test-get")));

            var host = builder.Build();
            await host.StartAsync();

            var client = new HttpClient(new DialMessageHandler(new TestDialer("test-get")));
            var result = await client.GetStringAsync("http://localhost/api/e2e-tests/hello-world");

            Assert.Equal("Hello World", result);

            await host.StopAsync();
        }
Пример #29
0
        private static void RunHost()
        {
            var hostBuilder = new WebHostBuilder()
                              .UseKestrel()
                              .UseIISIntegration()
                              .UseEnvironment(AppInfo.Configuration)
                              .UseContentRoot(Directory.GetCurrentDirectory())
                              .UseWebRoot(Path.Combine(Directory.GetCurrentDirectory(), AppInfo.FileServer?.PublicRootPath ?? "wwwroot"))
                              .UseUrls(AppInfo.HostUrl)
                              .UseStartup <Startup>();


            var host = hostBuilder.Build();

            host.Run();
        }
Пример #30
0
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .UseStartup <Startup>()
                       .UseApplicationInsights();



            host.CaptureStartupErrors(true);
            host.UseSetting("detailedErrors", "true");

            host.Build().Run();
        }
Пример #31
0
        public void WebHostAddCloudFoundryConfiguration_Adds()
        {
            // arrange
            var hostbuilder = new WebHostBuilder();

            hostbuilder.Configure(builder => { });

            // act
            hostbuilder.AddCloudFoundryConfiguration();
            var host = hostbuilder.Build();

            // assert
            var cfg = host.Services.GetService(typeof(IConfiguration)) as IConfigurationRoot;

            Assert.Contains(cfg.Providers, ctype => ctype is CloudFoundryConfigurationProvider);
        }
Пример #32
0
        public void AspNetCoreShouldBeOperational()
        {
            var builder = new WebHostBuilder()
                          .UseKestrel()
                          .UseStartup <Startup>();
            var host = builder.Build();

            host.Start();
            var address   = host.ServerFeatures.Get <IServerAddressesFeature>();
            var addr      = address.Addresses.First().ToString();
            var transport = new HttpClientTransport(addr + "/rpc");
            var resp      = transport.SendMessageAsync(new byte[] { 1, 2 }).Result;

            Assert.True(resp.SequenceEqual(new byte[] { 2, 1 }));
            host.Services.GetService <IApplicationLifetime>().StopApplication();
        }
        public void LibuvTransportCanBeManuallySelectedIndependentOfOrder()
        {
            var hostBuilder = new WebHostBuilder()
                              .UseKestrel()
                              .UseLibuv()
                              .Configure(app => { });

            Assert.IsType <LibuvTransportFactory>(hostBuilder.Build().Services.GetService <IConnectionListenerFactory>());

            var hostBuilderReversed = new WebHostBuilder()
                                      .UseLibuv()
                                      .UseKestrel()
                                      .Configure(app => { });

            Assert.IsType <LibuvTransportFactory>(hostBuilderReversed.Build().Services.GetService <IConnectionListenerFactory>());
        }
Пример #34
0
        public void allow_disable_running_database_migrations_in_ui_setup()
        {
            var webhost = new WebHostBuilder()
                          .UseStartup <DefaultStartup>()
                          .ConfigureServices(services =>
            {
                services
                .AddHealthChecksUI(setup => setup.DisableDatabaseMigrations())
                .AddInMemoryStorage();
            });

            var serviceProvider = webhost.Build().Services;
            var UISettings      = serviceProvider.GetService <IOptions <Settings> >().Value;

            UISettings.DisableMigrations.Should().Be(true);
        }
Пример #35
0
        public static void Main(string[] args)
        {
            var builder = new WebHostBuilder()
                          .UseStartup <Startup>()
                          .UseUrls("http://*:8080;https://*:8081")
                          .UseKestrel(options =>
            {
                options.UseHttps("testCert.pfx", "testPassword");
            });

            var host = builder.Build();

            Console.WriteLine("Listening on https://*:8080 and https://*:8081 ...");

            host.Run();
        }
Пример #36
0
        public static void Main(string[] args)
        {
            IWebHostBuilder builder = new WebHostBuilder();

            builder.ConfigureServices(s =>
            {
                s.AddSingleton(builder);
            });
            builder.UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseUrls("http://*:8000")
            .UseStartup <Startup>();
            var host = builder.Build();

            host.Run();
        }
        public void fail_to_register_sql_server_with_no_connection_string()
        {
            var hostBuilder = new WebHostBuilder()
                              .ConfigureAppConfiguration(config =>
            {
                config.Sources.Clear();

                config.AddInMemoryCollection(new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("storage_provider", StorageProviderEnum.SqlServer.ToString())
                });
            })
                              .UseStartup <Startup>();

            Assert.Throws <ArgumentNullException>(() => hostBuilder.Build());
        }
Пример #38
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Running demo with Kestrel.");

            //This is our webhostBuiler
            var builder = new WebHostBuilder()
                          //.UseContentRoot(Directory.GetCurrentDirectory())
                          .UseStartup <Startup>()
                          .UseKestrel()
                          .UseUrls("http://localhost:5000");
            //Build the webhost
            var host = builder.Build();

            //run
            host.Run();
        }
        public void register_server_addresses_service_to_resolve_relative_uris_using_application_builder()
        {
            var webHostBuilder = new WebHostBuilder()
                                 .UseKestrel()
                                 .ConfigureServices(services =>
            {
                services.
                AddHealthChecksUI();
            }).Configure(app => app.UseHealthChecksUI());

            var serviceProvider        = webHostBuilder.Build().Services;
            var serverAddressesService = serviceProvider.GetRequiredService <ServerAddressesService>();

            serverAddressesService.Should().NotBeNull();
            serverAddressesService.Addresses.Should().NotBeNull();
        }
Пример #40
0
        public LocService ObtenerLocService()
        {
            var builder = new WebHostBuilder()
                          .UseStartup <Startup>()
                          .ConfigureAppConfiguration((context, config) =>
            {
                config.SetBasePath(Path.Combine(
                                       Directory.GetCurrentDirectory(),
                                       "..", "..", "..", "..", "CaducaRest"));
                config.AddJsonFile("appsettings.json");
            });
            var scope = builder.Build().Services.CreateScope();

            return(scope.ServiceProvider
                   .GetRequiredService <LocService>());
        }
Пример #41
0
        public void SocketsTransportCanBeManuallySelectedIndependentOfOrder()
        {
            var hostBuilder = new WebHostBuilder()
                              .UseKestrel()
                              .UseSockets()
                              .Configure(app => { });

            Assert.IsType <SocketTransportFactory>(hostBuilder.Build().Services.GetService <ITransportFactory>());

            var hostBuilderReversed = new WebHostBuilder()
                                      .UseSockets()
                                      .UseKestrel()
                                      .Configure(app => { });

            Assert.IsType <SocketTransportFactory>(hostBuilderReversed.Build().Services.GetService <ITransportFactory>());
        }
        public void fail_with_invalid_storage_provider_value()
        {
            var hostBuilder = new WebHostBuilder()
                              .ConfigureAppConfiguration(config =>
            {
                config.Sources.Clear();

                config.AddInMemoryCollection(new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("storage_provider", "invalidvalue")
                });
            })
                              .UseStartup <Startup>();

            Assert.Throws <ArgumentException>(() => hostBuilder.Build());
        }
Пример #43
0
        public static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .AddInMemoryCollection(new [] { new KeyValuePair<string, string>("Server.Urls", "http://localhost:2100") })
            .Build();

            var host = new WebHostBuilder(config, true)
                .UseStartup<Startup>()
                .UseServices(ConfigureServices)
                .UseServer("Microsoft.AspNet.Server.Kestrel");

            var hostingEngine = host.Build();

            _website = hostingEngine.Start();

            Console.WriteLine("hai");
            Console.ReadKey();
        }
Пример #44
0
        protected override void OnStart(string[] args)
        {
            _log.WriteEntry("Program > OnStart > Enter");
            try
            {

                var builder = new WebHostBuilder(_serviceProvider, Configuration);
                builder.UseServer("Microsoft.AspNet.Server.WebListener");

                _hostingEngine = builder.Build();
                _shutdownServerDisposable = _hostingEngine.Start();
            }
            catch (Exception ex)
            {
                _log.WriteEntry(ex.Message);
            }
            _log.WriteEntry("Program > OnStart > Exit");
        }
Пример #45
0
        protected override void OnStart(string[] args)
        {
            var configSource = new MemoryConfigurationSource();
            configSource.Add("server.urls", "http://localhost:5000");

            var config = new ConfigurationBuilder(configSource).Build();
            var builder = new WebHostBuilder(_serviceProvider, config);
            builder.UseServer("Microsoft.AspNet.Server.Kestrel");
            builder.UseServices(services => services.AddMvc());
            builder.UseStartup(appBuilder =>
            {
                appBuilder.UseDefaultFiles();
                appBuilder.UseStaticFiles();
                appBuilder.UseMvc();
            });

            _hostingEngine = builder.Build();
            _shutdownServerDisposable = _hostingEngine.Start();
        }
Пример #46
0
        public void Start()
        {
            var configSource = new JsonConfigurationProvider($@"{_applicationEnvironment.ApplicationBasePath}\config.json");
            
            var config = new ConfigurationBuilder()
                .Add(configSource)
                .Build();

            var builder = new WebHostBuilder(config);
            builder.UseServer("Microsoft.AspNet.Server.Kestrel");
            builder.UseServices(services => services.AddMvc());
            builder.UseStartup(appBuilder =>
            {
                appBuilder.UseDefaultFiles();
                appBuilder.UseStaticFiles();
                appBuilder.UseMvc();
            });

            _application = builder.Build().Start();
        }
        public async Task ZeroToTenThreads(int threadCount)
        {
            var config = new ConfigurationBuilder()
                .AddInMemoryCollection(new Dictionary<string, string>
                {
                    { "server.urls", "http://localhost:8790/" }
                })
                .Build();

            var hostBuilder = new WebHostBuilder(config);
            hostBuilder.UseServer("Microsoft.AspNet.Server.Kestrel");
            hostBuilder.UseStartup(app =>
            {
                var serverInfo = app.ServerFeatures.Get<IKestrelServerInformation>();
                serverInfo.ThreadCount = threadCount;
                app.Run(context =>
                {
                    return context.Response.WriteAsync("Hello World");
                });
            });            

            using (var app = hostBuilder.Build().Start())
            {
                using (var client = new HttpClient())
                {
                    // Send 20 requests just to make sure we don't get any failures
                    var requestTasks = new List<Task<string>>();
                    for (int i = 0; i < 20; i++)
                    {
                        var requestTask = client.GetStringAsync("http://localhost:8790/");
                        requestTasks.Add(requestTask);
                    }
                    
                    foreach (var result in await Task.WhenAll(requestTasks))
                    {
                        Assert.Equal("Hello World", result);
                    }
                }
            }
        }
Пример #48
0
        protected override void OnStart(string[] args)
        {
            var configSource = new JsonConfigurationProvider($@"{_applicationEnvironment.ApplicationBasePath}\config.json");

            var config = new ConfigurationBuilder().Add(configSource).Build();
            var builder = new WebHostBuilder(config);
            builder.UseServer("Microsoft.AspNet.Server.Kestrel");
            builder.UseServices(services => services.AddMvc());
            builder.UseStartup(appBuilder =>
            {
                appBuilder.UseStaticFiles();

                appBuilder.UseMvc(routes =>
                {
                    routes.MapRoute(
                        "Default",
                        "{controller}/{action}",
                        new { controller = "home", action = "index" });
                });
            });

            _hostingEngine = builder.Build();
            _shutdownServerDisposable = _hostingEngine.Start();
        }
Пример #49
0
        public static void Main(string[] args)
        {
            var hostingConfig = new ConfigurationBuilder()
                .AddJsonFile("hosting.json", optional: true)
                .AddEnvironmentVariables()
                .AddEnvironmentVariables(prefix: "ASPNET_")
                .AddCommandLine(args)
                .Build();

            var hostBuilder = new WebHostBuilder(hostingConfig, captureStartupErrors: true);
            hostBuilder.UseStartup(typeof(Startup));

            var host = hostBuilder.Build();

            using (var app = host.Start())
            {
                // Echo out the addresses we're listening on
                var hostingEnv = app.Services.GetRequiredService<IHostingEnvironment>();
                Console.WriteLine("Hosting environment: " + hostingEnv.EnvironmentName);

                var serverAddresses = app.ServerFeatures.Get<IServerAddressesFeature>();
                if (serverAddresses != null)
                {
                    foreach (var address in serverAddresses.Addresses)
                    {
                        Console.WriteLine("Now listening on: " + address);
                    }
                }

                Console.WriteLine("Application started. Press Ctrl+C to shut down.");

                var appLifetime = app.Services.GetRequiredService<IApplicationLifetime>();

                // Run the interaction on a separate thread as we don't have Console.KeyAvailable on .NET Core so can't
                // do a pre-emptive check before we call Console.ReadKey (which blocks, hard)
                var interactiveThread = new Thread(() =>
                {
                    Console.WriteLine();
                    Console.WriteLine("Press 'C' to force GC or any other key to display GC stats");

                    while (true)
                    {
                        var key = Console.ReadKey(intercept: true);

                        if (key.Key == ConsoleKey.C)
                        {
                            Console.WriteLine();
                            Console.Write("Forcing GC...");
                            GC.Collect();
                            Console.WriteLine(" done!");
                        }
                        else
                        {
                            Console.WriteLine();
                            Console.WriteLine($"Allocated: {GetAllocatedMemory()}");
                            Console.WriteLine($"Gen 0: {GC.CollectionCount(0)}, Gen 1: {GC.CollectionCount(1)}, Gen 2: {GC.CollectionCount(2)}");
                        }
                    }
                });

                // Handle Ctrl+C in order to gracefully shutdown the web server
                Console.CancelKeyPress += (sender, eventArgs) =>
                {
                    Console.WriteLine();
                    Console.WriteLine("Shutting down application...");

                    appLifetime.StopApplication();

                    eventArgs.Cancel = true;
                };

                interactiveThread.Start();

                appLifetime.ApplicationStopping.WaitHandle.WaitOne();
            }
        }
Пример #50
0
        protected override void OnStart(string[] args)
        {
            try
            {

                var configProvider = new MemoryConfigurationProvider();
                configProvider.Add("server.urls", "http://localhost:5000");

                var config = new ConfigurationBuilder()
                    .Add(configProvider)
                    .Build();

                var builder = new WebHostBuilder(config);
                builder.UseServer("Microsoft.AspNet.Server.Kestrel");
                builder.UseServices(services =>
                {
                    services.AddMvc(opts =>
                    {
                        // none
                    });
                });

                builder.UseStartup(appBuilder =>
                {
                    appBuilder.Use(async (ctx, next) =>
                    {
                        try
                        {
                            await next();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    });

                    appBuilder.UseDefaultFiles();
                    appBuilder.UseStaticFiles();
                    appBuilder.UseMvc();

                    //if (env.IsDevelopment())
                    {
                        appBuilder.UseBrowserLink();
                        appBuilder.UseDeveloperExceptionPage();
                        appBuilder.UseDatabaseErrorPage();
                    }
                });

                var hostingEngine = builder.Build();
                _application = hostingEngine.Start();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("error in OnStart: " + ex);
                throw;
            }
        }
 private DbContext TryCreateContextUsingAppCode(Type dbContextType, ModelType startupType)
 {
     var hostBuilder = new WebHostBuilder();
     if (startupType != null)
     {
         var reflectedStartupType = dbContextType.GetTypeInfo().Assembly.GetType(startupType.FullName);
         if (reflectedStartupType != null)
         {
             hostBuilder.UseStartup(reflectedStartupType);
         }
     }
     var appServices = hostBuilder.Build().ApplicationServices;
     return appServices.GetService(dbContextType) as DbContext;
 }