public void Main(string[] args) { // Allow the location of the ini file to be specified via a --config command line arg var tempBuilder = new ConfigurationBuilder().AddCommandLine(args); var tempConfig = tempBuilder.Build(); var configFilePath = tempConfig[ConfigFileKey] ?? HostingIniFile; var appBasePath = _serviceProvider.GetRequiredService<IApplicationEnvironment>().ApplicationBasePath; var builder = new ConfigurationBuilder(appBasePath); builder.AddIniFile(configFilePath, optional: true); builder.AddEnvironmentVariables(); builder.AddCommandLine(args); var config = builder.Build(); var host = new WebHostBuilder(_serviceProvider, config).Build(); using (host.Start()) { Console.WriteLine("Started"); var appShutdownService = host.ApplicationServices.GetRequiredService<IApplicationShutdown>(); Console.CancelKeyPress += (sender, eventArgs) => { appShutdownService.RequestShutdown(); // Don't terminate the process immediately, wait for the Main thread to exit gracefully. eventArgs.Cancel = true; }; appShutdownService.ShutdownRequested.WaitHandle.WaitOne(); } }
private static IApplication CreateWebHost(IConfigurationRoot config) { var webHostBuilder = new WebHostBuilder(config) .UseServer("Microsoft.AspNet.Server.WebListener") .Build(); return webHostBuilder.Start(); }
static void Main(string[] args) { var builder = new WebHostBuilder() .UseKestrel() .ConfigureServices(s => s.AddMvc()) .Configure(a => a.UseMvc()) .UseUrls("http://+:80") .Build(); builder.Start(); Thread.Sleep(Timeout.Infinite); }
private void ClientDisconnect_NoWriteExceptionThrown(ServerType serverType) { var interval = TimeSpan.FromSeconds(15); var requestReceived = new ManualResetEvent(false); var requestCacelled = new ManualResetEvent(false); var responseComplete = new ManualResetEvent(false); Exception exception = null; var builder = new WebHostBuilder() .UseWebRoot(Path.Combine(AppContext.BaseDirectory)) .Configure(app => { app.Use(async(context, next) => { try { requestReceived.Set(); Assert.True(requestCacelled.WaitOne(interval), "not cancelled"); Assert.True(context.RequestAborted.WaitHandle.WaitOne(interval), "not aborted"); await next(); } catch (Exception ex) { exception = ex; } responseComplete.Set(); }); app.UseStaticFiles(); }); if (serverType == ServerType.HttpSys) { builder.UseHttpSys(); } else if (serverType == ServerType.Kestrel) { builder.UseKestrel(); } using (var server = builder.Start(TestUrlHelper.GetTestUrl(serverType))) { // We don't use HttpClient here because it's disconnect behavior varies across platforms. var socket = SendSocketRequestAsync(server.GetAddress(), "/TestDocument1MB.txt"); Assert.True(requestReceived.WaitOne(interval), "not received"); socket.LingerState = new LingerOption(true, 0); socket.Dispose(); requestCacelled.Set(); Assert.True(responseComplete.WaitOne(interval), "not completed"); Assert.Null(exception); } }
public static IDisposable CreateServer(ILoggerFactory loggerFactory, out int port, Func <HttpContext, Task> app, Action <WebSocketOptions> configure = null) { configure = configure ?? (o => { }); Action <IApplicationBuilder> startup = builder => { builder.Use(async(ct, next) => { try { // Kestrel does not return proper error responses: // https://github.com/aspnet/KestrelHttpServer/issues/43 await next(); } catch (Exception ex) { if (ct.Response.HasStarted) { throw; } ct.Response.StatusCode = 500; ct.Response.Headers.Clear(); await ct.Response.WriteAsync(ex.ToString()); } }); builder.UseWebSockets(); builder.Run(c => app(c)); }; var configBuilder = new ConfigurationBuilder(); configBuilder.AddInMemoryCollection(); var config = configBuilder.Build(); config["server.urls"] = $"http://127.0.0.1:0"; var host = new WebHostBuilder() .ConfigureServices(s => { s.AddWebSockets(configure); s.AddSingleton(loggerFactory); }) .UseConfiguration(config) .UseKestrel() .Configure(startup) .Build(); host.Start(); port = host.GetPort(); return(host); }
static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>() .UseUrls("http://localhost:5000") .Build(); host.Start(); Console.WriteLine("Server is started..."); Console.ReadKey(); }
public Tester() { var port = FreeTcpPort(); Host = new WebHostBuilder().UseKestrel(opt => { opt.ListenLocalhost(port); }).UseStartup <Startup>().Build(); Host.Start(); RateLimitService = Host.Services.GetService <IRateLimitService>(); Client = new HttpClient(); Client.BaseAddress = new Uri("http://localhost:" + port); }
public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseStartup <Startup>() .Build(); using (host) { host.Start(); Console.ReadLine(); } }
public static void Init(IConfigurationProvider configurationProvider, Func <IServiceCollection, IContainer> registerServices) { Startup.RegisterServices = registerServices; var host = new WebHostBuilder() .UseKestrel() .UseUrls(configurationProvider.QueryServiceListenUrl) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>() .Build(); host.Start(); }
public void Init() { Host = new WebHostBuilder() .ConfigureServices(s => { s.AddSingleton(Session); }) .ConfigureServices(s => { s.AddSingleton(FileRepository); }) .ConfigureServices(s => { s.AddSingleton(MessageRepository); }) .ConfigureServices(s => { s.AddSingleton(SaveSession); }) .UseKestrel() .UseUrls($"http://*:{Session.ProxyPort}") .UseStartup <ProxyStartup>() .Build(); Host.Start(); }
private static IWebHost StartWebHost(long?maxRequestBufferSize, byte[] expectedBody, ManualResetEvent startReadingRequestBody, ManualResetEvent clientFinishedSendingRequestBody) { var host = new WebHostBuilder() .UseKestrel(options => { options.MaxRequestBufferSize = maxRequestBufferSize; options.UseHttps(@"TestResources/testCert.pfx", "testPassword"); }) .UseUrls("http://127.0.0.1:0/", "https://127.0.0.1:0/") .UseContentRoot(Directory.GetCurrentDirectory()) .Configure(app => app.Run(async context => { startReadingRequestBody.WaitOne(); var buffer = new byte[expectedBody.Length]; var bytesRead = 0; while (bytesRead < buffer.Length) { bytesRead += await context.Request.Body.ReadAsync(buffer, bytesRead, buffer.Length - bytesRead); } clientFinishedSendingRequestBody.WaitOne(); // Verify client didn't send extra bytes if (context.Request.Body.ReadByte() != -1) { context.Response.StatusCode = 500; await context.Response.WriteAsync("Client sent more bytes than expectedBody.Length"); return; } // Verify bytes received match expectedBody for (int i = 0; i < expectedBody.Length; i++) { if (buffer[i] != expectedBody[i]) { context.Response.StatusCode = 500; await context.Response.WriteAsync($"Bytes received do not match expectedBody at position {i}"); return; } } await context.Response.WriteAsync($"bytesRead: {bytesRead.ToString()}"); })) .Build(); host.Start(); return(host); }
public async Task ReturnsFileForDefaultPattern() { var builder = new WebHostBuilder() .ConfigureServices(services => { services.AddRouting(); services.AddSingleton(LoggerFactory); }) .UseKestrel() .UseWebRoot(AppContext.BaseDirectory) .Configure(app => { var environment = app.ApplicationServices.GetRequiredService <IWebHostEnvironment>(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.Map("/hello", context => { return(context.Response.WriteAsync("Hello, world!")); }); endpoints.MapFallbackToFile("default.html", new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(environment.WebRootPath, "SubFolder")), }); }); }); using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) { var environment = server.Services.GetRequiredService <IWebHostEnvironment>(); using (var client = new HttpClient { BaseAddress = new Uri(server.GetAddress()) }) { var response = await client.GetAsync("hello"); var responseText = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Hello, world!", responseText); response = await client.GetAsync("/"); var responseContent = await response.Content.ReadAsByteArrayAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); AssertFileEquals(environment, "SubFolder/default.html", responseContent); } } }
private IWebHost BuildAndStartServer() { // By setting the port number to 0 the TCP stack will assign the next available port. const string url = "http://127.0.0.1:0"; var host = new WebHostBuilder() .UseKestrel() .Configure(app => { app.Run(HttpRequestHandler); }); return(host.Start(url)); }
static void HttpServe() { var wh = new WebHostBuilder() .UseKestrel() .UseStartup <Startup>() .Build(); wh.Start(); new Thread(AutoBot) { IsBackground = true }.Start(); wh.WaitForShutdown(); }
private IWebHost CreateHost(ServerOptions options) { var host = Utils.TryUntilMakeIt(() => { var h = new WebHostBuilder() .UseStartup <Startup>() .UseTCPServer(options) .Build(); h.Start(); return(h); }); return(host); }
public void Start() { var startup = new AspNetCoreStartup <T>(_format); _host = new WebHostBuilder() .UseKestrel(opt => opt.Limits.MaxRequestBodySize = 180000000) .ConfigureServices(startup.ConfigureServices) .Configure(startup.Configure) .UseUrls($"http://localhost:{_port}") .Build(); _host.Start(); InitializeClients(); }
public static void Start(IResultProcessor resultProcessor, int listeningPort) { var host = new WebHostBuilder() .UseUrls($"http://*:{listeningPort}") .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureServices((c, s) => { s.AddSingleton <IResultProcessor>(resultProcessor); }) .UseStartup <WebApiStartup>() .Build(); host.Start(); }
public void use_in_app_with_ambigious_references() { var builder = new WebHostBuilder(); builder .UseLamar() .UseMetrics() .UseUrls("http://localhost:5002") .UseServer(new NulloServer()) .UseApplicationInsights() .UseStartup <Startup>(); var failures = new List <Type>(); using (var host = builder.Start()) { var container = host.Services.ShouldBeOfType <Container>(); var errors = container.Model.AllInstances.Where(x => x.Instance.ErrorMessages.Any()) .SelectMany(x => x.Instance.ErrorMessages).ToArray(); if (errors.Any()) { throw new Exception(errors.Join(", ")); } foreach (var instance in container.Model.AllInstances.Where(x => !x.ServiceType.IsOpenGeneric())) { instance.Resolve().ShouldNotBeNull(); // try // { // // } // catch (Exception e) // { // failures.Add(instance.ServiceType); // } } } if (failures.Any()) { throw new Exception(failures.Select(x => x.FullNameInCode()).Join(Environment.NewLine)); } }
private IWebHost StartDependencyServiceHost(string fixerApiUrl, DependencyServiceStartupSetting dependencyServiceStartupSetting) { var host = new WebHostBuilder() .ConfigureServices(services => { services.AddSingleton(dependencyServiceStartupSetting); }) .UseKestrel() .UseUrls(fixerApiUrl) .UseStartup <DependencyServiceStartup>() .Build(); host.Start(); return(host); }
public static IDisposable Start(out string tokenEndpointUri) { var port = GetFreePort(); var uri = $"http://localhost:{port}"; tokenEndpointUri = $"{uri}/oauth2/token"; var mockHost = new WebHostBuilder() .UseUrls(uri) .UseKestrel() .Configure(new MockServerImpl(tokenEndpointUri).Configure) .Build(); mockHost.Start(); return(mockHost); }
// Entry point for the application. public static void Main(string[] args) { var config = new ConfigurationBuilder().AddCommandLine(args).Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseStartup <StartupBlockingOnStart>() .Build(); using (host) { host.Start(); Console.ReadLine(); } }
public void Does_return_new_Scoped_dependency_per_request() { using (var host = new WebHostBuilder() .UseKestrel() .UseStartup <ReqeustScopeStartup>() .UseUrls(Config.AbsoluteBaseUri) .Build()) { host.Start(); 5.Times(i => Config.AbsoluteBaseUri.GetStringFromUrl()); Assert.That(NetCoreScoped.count, Is.GreaterThanOrEqualTo(5)); } }
public void GetCart() { using (var host = new WebHostBuilder() .UseUrls(BaseUrl) .UseKestrel() .UseStartup <Startup>() .Build()) { host.Start(); var cart = Client.GetCartByIdWithHttpMessagesAsync(Guid.NewGuid(), Version); Assert.Equal(HttpStatusCode.OK, cart.Result.Response.StatusCode); } }
/// <summary> /// Starts listening at the specified port. /// </summary> public void Start() { Startup.Listener = this; m_hostBuilder = new WebHostBuilder(); HttpsConnectionAdapterOptions httpsOptions = new HttpsConnectionAdapterOptions(); httpsOptions.CheckCertificateRevocation = false; httpsOptions.ClientCertificateMode = ClientCertificateMode.NoCertificate; httpsOptions.ServerCertificate = m_serverCert; #if NET462 // note: although security tools recommend 'None' here, // it only works on .NET 4.6.2 if Tls12 is used #pragma warning disable CA5398 // Avoid hardcoded SslProtocols values httpsOptions.SslProtocols = SslProtocols.Tls12; #pragma warning restore CA5398 // Avoid hardcoded SslProtocols values #else httpsOptions.SslProtocols = SslProtocols.None; #endif bool bindToSpecifiedAddress = true; UriHostNameType hostType = Uri.CheckHostName(m_uri.Host); if (hostType == UriHostNameType.Dns || hostType == UriHostNameType.Unknown || hostType == UriHostNameType.Basic) { bindToSpecifiedAddress = false; } if (bindToSpecifiedAddress) { IPAddress ipAddress = IPAddress.Parse(m_uri.Host); m_hostBuilder.UseKestrel(options => { options.Listen(ipAddress, m_uri.Port, listenOptions => { listenOptions.UseHttps(httpsOptions); }); }); } else { m_hostBuilder.UseKestrel(options => { options.ListenAnyIP(m_uri.Port, listenOptions => { listenOptions.UseHttps(httpsOptions); }); }); } m_hostBuilder.UseContentRoot(Directory.GetCurrentDirectory()); m_hostBuilder.UseStartup <Startup>(); m_host = m_hostBuilder.Start(Utils.ReplaceLocalhost(m_uri.ToString())); }
private ChutzpahWebServerHost BuildHost(string rootPath, int defaultPort, string builtInDependencyFolder) { var attemptLimit = Constants.WebServerCreationAttemptLimit; var success = false; do { // We can try multiple times to build the webserver. The reason is there is a possible race condition where // between when we find a free port and when we start the server that port may have been taken. To mitigate this we // can retry to hopefully avoid this issue. attemptLimit--; var port = FindFreePort(defaultPort); try { ChutzpahTracer.TraceInformation("Creating Web Server Host at path {0} and port {1}", rootPath, port); var host = new WebHostBuilder() .UseUrls($"http://localhost:{port}") .UseContentRoot(rootPath) .UseWebRoot("") .UseKestrel() .Configure((app) => { var env = (IHostingEnvironment)app.ApplicationServices.GetService(typeof(IHostingEnvironment)); app.UseStaticFiles(new StaticFileOptions { FileProvider = new ChutzpahServerFileProvider(env.ContentRootPath, builtInDependencyFolder) }); app.Run(async(context) => { await context.Response.WriteAsync("Chutzpah Web Server"); }); }) .Build(); host.Start(); success = true; return(ChutzpahWebServerHost.Create(host, rootPath, port)); } catch (Exception ex) when((ex is UvException || ex is IOException) && attemptLimit > 0) { ChutzpahTracer.TraceError(ex, "Unable to create web server host at path {0} and port {1}. Trying again...", rootPath, port); } }while (!success && attemptLimit > 0); throw new ChutzpahException("Failed to create web server. This should never be hit!"); }
public void GetItemFromBasket() { using (var host = new WebHostBuilder() .UseUrls("http://localhost:54578") .UseKestrel() .UseStartup <API.Startup>() .Build()) { host.Start(); var client = new ClientSdk.BasketApi(new Uri("http://localhost:54578")); var basket = client.ApiBasketByCustomerIdGetWithHttpMessagesAsync(1); Equals(HttpStatusCode.OK, basket.Result.Response.StatusCode); } }
public void ClearBasket() { using (var host = new WebHostBuilder() .UseUrls("http://localhost:54578") .UseKestrel() .UseStartup <API.Startup>() .Build()) { host.Start(); var client = new ClientSdk.BasketApi(new Uri("http://localhost:54578")); var result = client.ApiBasketClearDeleteWithHttpMessagesAsync(1); Equals(HttpStatusCode.OK, result.Result.Response.StatusCode); } }
public static Uri EnableWebUI(this TorrentClient client, Uri listenUri) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseUrls(listenUri.ToString()) .UseStartup <Startup>() .UseApplicationInsights() .ConfigureServices(s => { s.Add(new ServiceDescriptor(typeof(TorrentClient), client)); }) .Build(); host.Start(); return(listenUri); }
//https://github.com/aspnet/Hosting/blob/dev/src/Microsoft.AspNet.Hosting/Program.cs public Task<int> Main(string[] args) { //Add command line configuration source to read command line parameters. var builder = new ConfigurationBuilder().AddCommandLine(args); var config = builder.Build(); var host = new WebHostBuilder(_serviceProvider, config, true) .UseServer("Microsoft.AspNet.Server.Kestrel") .Build(); using (var app = host.Start()) { var orchardHost = new OrchardHost(app.Services, System.Console.In, System.Console.Out, args); return Task.FromResult( (int)orchardHost.Run()); } }
public static void Main(string[] args) { var builder = new WebHostBuilder(); builder // Replaces the built in DI container // with Lamar .UseLamar() // Normal ASP.Net Core bootstrapping .UseUrls("http://localhost:5002") .UseKestrel() .UseStartup <Startup>(); builder.Start(); }
public static dynamic Start() { dynamic host = new WebHostBuilder() .UseUrls("http://localhost:23897") .UseKestrel(options => { options.NoDelay = true; options.UseConnectionLogging(); }) .UseStartup <Startup>() .Build(); host.Start(); return(host); }
/// <summary> /// Start Web API. /// </summary> public override void Open() { var host = new WebHostBuilder() .ConfigureLogging((hostingContext, logging) => { logging.AddProvider(new LogProvider(Logger)); logging.AddDebug(); }) .UseKestrel() .UseUrls(Settings.Url) .Configure(ConfigureApps) .Build(); host.Start(); this.host = host; }
public async Task ReturnsFileForCustomPattern() { var builder = new WebHostBuilder() .ConfigureServices(services => { services.AddRouting(); services.AddSingleton(LoggerFactory); }) .UseKestrel() .UseWebRoot(AppContext.BaseDirectory) .Configure(app => { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.Map("/hello", context => { return(context.Response.WriteAsync("Hello, world!")); }); endpoints.MapFallbackToFile("/prefix/{*path:nonfile}", "TestDocument.txt"); }); }); using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) { var environment = server.Services.GetRequiredService <IWebHostEnvironment>(); using (var client = new HttpClient { BaseAddress = new Uri(server.GetAddress()) }) { var response = await client.GetAsync("hello"); var responseText = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Hello, world!", responseText); response = await client.GetAsync("prefix/Some-Path"); var responseContent = await response.Content.ReadAsByteArrayAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); AssertFileEquals(environment, "TestDocument.txt", responseContent); } } }
public static IDisposable CreateServer(Func<HttpContext, Task> app) { Action<IApplicationBuilder> startup = builder => { builder.Use(async (ct, next) => { try { // Kestrel does not return proper error responses: // https://github.com/aspnet/KestrelHttpServer/issues/43 await next(); } catch (Exception ex) { if (ct.Response.HasStarted) { throw; } ct.Response.StatusCode = 500; ct.Response.Headers.Clear(); await ct.Response.WriteAsync(ex.ToString()); } }); builder.UseWebSockets(); builder.Run(c => app(c)); }; var configBuilder = new ConfigurationBuilder(); configBuilder.Add(new MemoryConfigurationSource()); var config = configBuilder.Build(); config["server.urls"] = "http://localhost:54321"; var host = new WebHostBuilder(CallContextServiceLocator.Locator.ServiceProvider, config) .UseServer("Microsoft.AspNet.Server.Kestrel") .UseStartup(startup) .Build(); return host.Start(); }