public async Task HeaderIsAdded() { var port = ServiceManagerConfig.GetNextAvailablePort(); var host = new WebHostBuilder() .UseKestrel() .UseUrls($"http://*:{port}") .UseStartup <Startup>() .Build(); host.Start(); try { var client = new HttpClient(); var result = await client.GetAsync($"http://localhost:{port}"); var content = await result.Content.ReadAsStringAsync(); Assert.Equal("Hello", content); Assert.Equal("FunnyHeader", result.Headers.Trailer.First()); } finally { host.Dispose(); } }
public async Task CanAuthenticateWithNtlm() { var host = new WebHostBuilder() .UseKestrel((ops) => { ops.UseWindowsAuthentication(); }) .UseUrls($"http://*:{55555}") .UseStartup <Startup>() .Build(); host.Start(); try { var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }); var result = await client.GetAsync($"http://localhost:55555"); var name = await result.Content.ReadAsStringAsync(); Assert.Equal(System.Security.Principal.WindowsIdentity.GetCurrent().Name, name); } finally { host.Dispose(); } }
static void Main(string[] args) { ServicePointManager.DefaultConnectionLimit = 100; IWebHost host = null; var processor = new ConsoleLoggerProcessor(); CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor); var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(loggerProvider); var logger = loggerFactory.CreateLogger("Configuration"); try { var conf = new DefaultConfiguration() { Logger = logger }.CreateConfiguration(args); if (conf == null) { return; } host = new WebHostBuilder() .UseKestrel() .UseIISIntegration() .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(conf) .ConfigureLogging(l => { l.AddFilter("Microsoft", LogLevel.Error); l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical); l.AddProvider(new CustomConsoleLogProvider(processor)); }) .UseStartup <Startup>() .Build(); host.StartAsync().GetAwaiter().GetResult(); var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses; foreach (var url in urls) { logger.LogInformation("Listening on " + url); } host.WaitForShutdown(); } catch (ConfigException ex) { if (!string.IsNullOrEmpty(ex.Message)) { Logs.Configuration.LogError(ex.Message); } } finally { processor.Dispose(); if (host != null) { host.Dispose(); } loggerProvider.Dispose(); } }
public async Task SwitcherooSeesHttpFact() { var port = CondenserDotNet.Client.ServiceManagerConfig.GetNextAvailablePort(); var host = new WebHostBuilder() .UseKestrel((ops) => { ops.Switcheroo(); ops.UseHttps(Certificate); }) .UseUrls($"*://*:{port}") .UseStartup <Startup>() .Build(); host.Start(); try { var client = new HttpClient(); var result = await client.GetAsync($"http://localhost:{port}"); var isHttps = await result.Content.ReadAsStringAsync(); Assert.False(bool.Parse(isHttps)); } finally { host.Dispose(); } }
public static void Main(string[] args) { var stopwatch = Stopwatch.StartNew(); var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup <Startup>() .UseApplicationInsights() .Build(); host.Start(); using (var http = new HttpClient()) { var home = http.GetStringAsync("http://localhost:5000").Result; var headingLocation = home.IndexOf("Sample pages using ASP.NET Core MVC"); if (headingLocation < 0) { throw new Exception("Hmmm, can't find home page text"); } } host.Dispose(); stopwatch.Stop(); Console.WriteLine($"Time to start-up, retrieve home page, and shutdown: {stopwatch.Elapsed}"); }
public static void Main(string[] args) { var keyHandler = new KeyHandler(); // todo: IOC var environmentService = SwimbaitModule.GetEnvironmentService(); _multicastServer = new MulticastServer(environmentService); _multicastService = new MulticastService(environmentService); var _musicCastHost = new MusicCastHost(environmentService); //Add command line configuration source to read command line parameters. var builder = new ConfigurationBuilder(); var portsToListen = new [] { 80, EnvironmentService.SwimbaitDlnaPort, 51100 }; var urisToListen = portsToListen .ToList() .Select(p => $"http://{environmentService.IpAddress}:{p}"); var uriToListenString = string.Join(";", urisToListen); var config = builder .AddCommandLine(new[] { $"server.urls={uriToListenString}" }) .AddEnvironmentVariables() .Build(); _musicCastHost.RelayHost = IPAddress.Parse(config["Swimbait:RelayHost"]); // Dirty DI Startup._environmentService = environmentService; Startup._musicCastHost = _musicCastHost; var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseStartup <Startup>() .Build(); Console.WriteLine($"Starting the server. Listening on {uriToListenString}. Udp broadcasting to {environmentService.SubnetBroadcastIp}"); host.Start(); Console.WriteLine("Press 'Q' to stop the server"); Console.WriteLine("Press 'M' to send SSDP Multicast discovery"); Console.WriteLine("Press 'C' when ready to connect to the MusicCast app"); _multicastServer.Start(); keyHandler.KeyEvent += KeyHandler_KeyEvent; keyHandler.WaitForExit(); host.Dispose(); _multicastServer.Dispose(); }
/// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { var serviceFabricHostMarker = Environment.GetEnvironmentVariable("ServiceFabricHostMarker"); if (serviceFabricHostMarker != null) { try { // The ServiceManifest.XML file defines one or more service type names. // Registering a service maps a service type name to a .NET type. // When Service Fabric creates an instance of this service type, // an instance of the class is created in this host process. ServiceRuntime.RegisterServiceAsync( "EventManagement.UserManagement.WebType", context => new Web(context)).GetAwaiter().GetResult(); ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(Web).Name); // Prevents this host process from terminating so services keeps running. Thread.Sleep(Timeout.Infinite); } catch (Exception e) { ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString()); throw; } } else { IWebHost host = null; try { host = new WebHostBuilder() .UseHttpSys() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup <Startup>() .UseUrls("http://*:5002") .Build(); host.Run(); } finally { host?.Dispose(); } } }
public async Task SwitcherooSeesHttpsFact() { var port = CondenserDotNet.Client.ServiceManagerConfig.GetNextAvailablePort(); var host = new WebHostBuilder() .UseKestrel((ops) => { ops.Switcheroo(); ops.UseHttps(Certificate); }) .UseUrls($"*://*:{port}") .UseStartup <Startup>() .Build(); host.Start(); try { var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = (request, cert, chain, policy) => { return(true); } }); var result = await client.GetAsync($"https://localhost:{port}"); var isHttp = await result.Content.ReadAsStringAsync(); Assert.True(bool.Parse(isHttp)); } finally { host.Dispose(); } }
public async Task SwitcherooSeesHttpsFact() { var port = CondenserDotNet.Client.ServiceManagerConfig.GetNextAvailablePort(); var host = new WebHostBuilder() .UseKestrel((ops) => { //ops.Switcheroo(); ops.UseHttps(Certificate); }) .UseUrls($"https://*:{port}") .UseStartup <Startup>() .Build(); host.Start(); var t = Task.Run(() => { try { var client = new HttpClient(new HttpClientHandler() { }); var result = client.GetAsync($"https://localhost:{port}"); result.Wait(); var isHttps = result.Result.Content.ReadAsStringAsync(); isHttps.Wait(); Assert.True(bool.Parse(isHttps.Result)); } finally { host.Dispose(); } }); await t.ConfigureAwait(false); }
static void Main(string[] args) { ServicePointManager.DefaultConnectionLimit = 100; IWebHost host = null; var processor = new ConsoleLoggerProcessor(); CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor); using var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(loggerProvider); var logger = loggerFactory.CreateLogger("Configuration"); IConfiguration conf = null; try { // This is the only way that LoadArgs can print to console. Because LoadArgs is called by the HostBuilder before Logs.Configure is called conf = new DefaultConfiguration() { Logger = logger }.CreateConfiguration(args); if (conf == null) { return; } Logs.Configure(loggerFactory); new BTCPayServerOptions().LoadArgs(conf); Logs.Configure(null); ///// host = new WebHostBuilder() .UseKestrel() .UseIISIntegration() .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(conf) .ConfigureLogging(l => { l.AddFilter("Microsoft", LogLevel.Error); l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical); l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical); l.AddProvider(new CustomConsoleLogProvider(processor)); }) .UseStartup <Startup>() .Build(); host.StartWithTasksAsync().GetAwaiter().GetResult(); var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses; foreach (var url in urls) { logger.LogInformation("Listening on " + url); } host.WaitForShutdown(); } catch (ConfigException ex) { if (!string.IsNullOrEmpty(ex.Message)) { Logs.Configuration.LogError(ex.Message); } } catch (Exception e) when(PluginManager.IsExceptionByPlugin(e)) { var pluginDir = new DataDirectories().Configure(conf).PluginDir; PluginManager.DisablePlugin(pluginDir, e.Source); } finally { processor.Dispose(); if (host == null) { Logs.Configuration.LogError("Configuration error"); } if (host != null) { host.Dispose(); } Serilog.Log.CloseAndFlush(); loggerProvider.Dispose(); } }
private const long MAX_DEBUG_LOG_FILE_SIZE = 2000000; // If debug log is in use roll it every N MB. static void Main(string[] args) { ServicePointManager.DefaultConnectionLimit = 100; IWebHost host = null; var processor = new ConsoleLoggerProcessor(); CustomConsoleLogProvider loggerProvider = new CustomConsoleLogProvider(processor); var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(loggerProvider); var logger = loggerFactory.CreateLogger("Configuration"); try { // This is the only way that LoadArgs can print to console. Because LoadArgs is called by the HostBuilder before Logs.Configure is called var conf = new DefaultConfiguration() { Logger = logger }.CreateConfiguration(args); if (conf == null) { return; } Logs.Configure(loggerFactory); new BTCPayServerOptions().LoadArgs(conf); Logs.Configure(null); ///// host = new WebHostBuilder() .UseKestrel() .UseIISIntegration() .UseContentRoot(Directory.GetCurrentDirectory()) .UseConfiguration(conf) .ConfigureLogging(l => { l.AddFilter("Microsoft", LogLevel.Error); l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical); l.AddFilter("Microsoft.AspNetCore.Antiforgery.Internal", LogLevel.Critical); l.AddFilter("AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerHandler", LogLevel.Error); l.AddProvider(new CustomConsoleLogProvider(processor)); // Use Serilog for debug log file. var debugLogFile = BTCPayServerOptions.GetDebugLog(conf); if (string.IsNullOrEmpty(debugLogFile) != false) { return; } Serilog.Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Is(BTCPayServerOptions.GetDebugLogLevel(conf)) .WriteTo.File(debugLogFile, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: MAX_DEBUG_LOG_FILE_SIZE, rollOnFileSizeLimit: true, retainedFileCountLimit: 1) .CreateLogger(); l.AddSerilog(Serilog.Log.Logger); }) .UseStartup <Startup>() .Build(); host.StartWithTasksAsync().GetAwaiter().GetResult(); var urls = host.ServerFeatures.Get <IServerAddressesFeature>().Addresses; foreach (var url in urls) { logger.LogInformation("Listening on " + url); } host.WaitForShutdown(); } catch (ConfigException ex) { if (!string.IsNullOrEmpty(ex.Message)) { Logs.Configuration.LogError(ex.Message); } } finally { processor.Dispose(); if (host == null) { Logs.Configuration.LogError("Configuration error"); } if (host != null) { host.Dispose(); } Serilog.Log.CloseAndFlush(); loggerProvider.Dispose(); } }
public static void Main(string[] args) { var processor = new ConsoleLoggerProcessor(); Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, (a, b) => true, false, processor))); IWebHost host = null; try { var conf = new DefaultConfiguration() { Logger = Logs.Configuration }.CreateConfiguration(args); if (conf == null) { return; } ConfigurationBuilder builder = new ConfigurationBuilder(); host = new WebHostBuilder() .UseKestrel() .UseIISIntegration() .UseConfiguration(conf) .UseApplicationInsights() .ConfigureLogging(l => { l.AddFilter("Microsoft", LogLevel.Error); if (conf.GetOrDefault <bool>("verbose", false)) { l.SetMinimumLevel(LogLevel.Debug); } l.AddProvider(new CustomConsoleLogProvider()); }) .UseStartup <Startup>() .Build(); host.Run(); } catch (ConfigException ex) { if (!string.IsNullOrEmpty(ex.Message)) { Logs.Configuration.LogError(ex.Message); } } catch (CommandParsingException parsing) { Logs.Explorer.LogError(parsing.HelpText + "\r\n" + parsing.Message); } catch (Exception exception) { Logs.Explorer.LogError("Exception thrown while running the server"); Logs.Explorer.LogError(exception.ToString()); } finally { processor.Dispose(); if (host != null) { host.Dispose(); } } }
public static void Main(string[] args) { var processor = new ConsoleLoggerProcessor(); Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, (a, b) => true, null, processor))); IWebHost host = null; try { var conf = new DefaultConfiguration() { Logger = Logs.Configuration }.CreateConfiguration(args); if (conf == null) { return; } // Sanity check of the config, this is not strictly needed as it would happen down the line when the host is built // However, a bug in .NET Core fixed in 2.1 will prevent the app from stopping if an exception is thrown by the host // at startup. We need to remove this line later new ExplorerConfiguration().LoadArgs(conf); ConfigurationBuilder builder = new ConfigurationBuilder(); host = new WebHostBuilder() .UseKestrel() .UseIISIntegration() .UseConfiguration(conf) .ConfigureLogging(l => { l.AddFilter("Microsoft", LogLevel.Error); l.AddFilter("System.Net.Http.HttpClient", LogLevel.Critical); l.AddFilter("NBXplorer.Authentication.BasicAuthenticationHandler", LogLevel.Critical); if (conf.GetOrDefault <bool>("verbose", false)) { l.SetMinimumLevel(LogLevel.Debug); } l.AddProvider(new CustomConsoleLogProvider(processor)); }) .UseStartup <Startup>() .Build(); host.Run(); } catch (ConfigException ex) { if (!string.IsNullOrEmpty(ex.Message)) { Logs.Configuration.LogError(ex.Message); } } catch (CommandParsingException parsing) { Logs.Explorer.LogError(parsing.HelpText + "\r\n" + parsing.Message); } finally { processor.Dispose(); if (host != null) { host.Dispose(); } } }
/// <summary> /// 使用Let's Encrypt服務產生X509憑證 /// </summary> /// <param name="options">Kestrel伺服器監聽選項實例</param> /// <param name="savePassword">憑證儲存密碼</param> /// <param name="email">電子郵件</param> /// <param name="domains">網域</param> /// <returns>可等候程序之X509憑證二進制原始資料</returns> public static async Task <byte[]> CreateX509BinaryByLetsEncryptAsync(this ListenOptions options, string savePassword, string email, params string[] domains) { using (var client = new AcmeClient(WellKnownServers.LetsEncrypt)) { // Create new registration var account = await client.NewRegistraton("mailto:" + email); // Accept terms of services account.Data.Agreement = account.GetTermsOfServiceUri(); account = await client.UpdateRegistration(account); // Initialize authorization Dictionary <string, string> keyAuthStringMap = new Dictionary <string, string>(); List <Challenge> challenges = new List <Challenge>(); foreach (var domain in domains) { var authz = await client.NewAuthorization(new AuthorizationIdentifier { Type = AuthorizationIdentifierTypes.Dns, Value = domain }); // Comptue key authorization for http-01 var httpChallengeInfo = authz.Data.Challenges.Where(c => c.Type == ChallengeTypes.Http01).First(); challenges.Add(httpChallengeInfo); var keyAuthString = client.ComputeKeyAuthorization(httpChallengeInfo); keyAuthStringMap[httpChallengeInfo.Token] = keyAuthString; } IWebHost k = new WebHostBuilder() .UseKestrel() .UseUrls("http://*") .ConfigureServices(services => { services.AddRouting(); }) .Configure(app => { var trackPackageRouteHandler = new RouteHandler(context => { return(context.Response.WriteAsync($"404 Not Found")); }); var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler); routeBuilder.MapGet(".well-known/acme-challenge/{id}", context => { var result = keyAuthStringMap[context.GetRouteValue("id") as string]; Console.WriteLine("Server Call :" + context.GetRouteValue("id")); return(context.Response.WriteAsync(result)); }); var routes = routeBuilder.Build(); app.UseRouter(routes); Console.WriteLine("Server Start"); }) .Build(); k.Start(); // Do something to fullfill the challenge, // e.g. upload key auth string to well known path, or make changes to DNS await Task.Delay(10000); foreach (var challenge in challenges) { // Info ACME server to validate the identifier var httpChallenge = await client.CompleteChallenge(challenge); //httpChallenge. // Check authorization status var authz = await client.GetAuthorization(httpChallenge.Location); while (authz.Data.Status == EntityStatus.Pending) { await Task.Delay(3000); authz = await client.GetAuthorization(httpChallenge.Location); } } var csr = new CertificationRequestBuilder(); csr.AddName("CN", domains.First()); foreach (var domain in domains.Skip(1)) { csr.SubjectAlternativeNames.Add(domain); } var cert = await client.NewCertificate(csr); var pfxBuilder = cert.ToPfx(); var x509result = pfxBuilder.Build("letsEncrypt", savePassword); Console.WriteLine("Let's Encrypt OK"); var serviceLife = k.Services.GetService <IApplicationLifetime>(); serviceLife.StopApplication(); k.Dispose(); Console.WriteLine("Server Stop"); return(x509result); } }
public async Task WithAspNetCore() { var container = new FabricContainer(); container.ConfigureSerilogging(logConfiguration => logConfiguration.MinimumLevel.Information() .Enrich.FromLogContext() .WriteTo.LiterateConsole(outputTemplate: LiterateLogTemplate)); { var child = container.CreateChildContainer(); child.RegisterType <ILoggerFactory, LoggerFactory>(new ContainerControlledLifetimeManager()); var childchi = child.CreateChildContainer(); var first = childchi.Resolve <ILoggerFactory>(); //Singleton / containercontrolled lifetime. var second = child.Resolve <ILoggerFactory>(); Assert.AreEqual(first, second); // But IloggerFactory is not disposed at this point. var builder = new WebHostBuilder() .UseKestrel() .ConfigureServices((b, s) => { s.AddSingleton(child); }) .UseUnityServiceProvider(child) .UseStartup <TestStartup>() .UseContentRoot(Directory.GetCurrentDirectory()).Build(); //But when we dispose this, then ilogger factory will also get disposed. Why here but not above. (builder.Services as IDisposable).Dispose(); //ILoggerFactory is now disposed. } { var child = container.CreateChildContainer(); //Ilogger factory is the same, and therefore disposed and now this will fail. var builder = new WebHostBuilder() .UseKestrel() .ConfigureServices((b, s) => { s.AddSingleton(child); }) .UseUnityServiceProvider(child) .UseStartup <TestStartup>() .UseContentRoot(Directory.GetCurrentDirectory()).Build(); builder.Dispose(); } }