/// <summary> /// Runs a web application and returns a Task that only completes when the token is triggered or shutdown is triggered. /// </summary> /// <param name="host">The <see cref="IWebHost"/> to run.</param> /// <param name="token">The token to trigger shutdown.</param> public static async Task RunAsync(this IWebHost host, CancellationToken token = default) { // Wait for token shutdown if it can be canceled if (token.CanBeCanceled) { await host.RunAsync(token, shutdownMessage : null); return; } // If token cannot be canceled, attach Ctrl+C and SIGTERM shutdown var done = new ManualResetEventSlim(false); using (var cts = new CancellationTokenSource()) { var shutdownMessage = host.Services.GetRequiredService <WebHostOptions>().SuppressStatusMessages ? string.Empty : "Application is shutting down..."; using (var lifetime = new WebHostLifetime(cts, done, shutdownMessage: shutdownMessage)) { try { await host.RunAsync(cts.Token, "Application started. Press Ctrl+C to shut down."); } finally { done.Set(); } } } }
public override async Task <ExecutionResult> RunAsync() { await _webHost.RunAsync(); return(ExecutionResult.Ok); }
public async Task StartAsync(EndPoint endPoint) { var ipEndPoint = endPoint as IPEndPoint; try { var hostBuilder = new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel(options => { options.Listen(ipEndPoint); }) .ConfigureServices(ConfigureServices) .ConfigureLogging((logger) => { logger.AddConfiguration( CPlatform.AppConfig.GetSection("Logging")); }) .Configure(AppResolve); if (Directory.Exists(CPlatform.AppConfig.ServerOptions.WebRootPath)) { hostBuilder = hostBuilder.UseWebRoot(CPlatform.AppConfig.ServerOptions.WebRootPath); } _host = hostBuilder.Build(); _lifetime.ServiceEngineStarted.Register(async() => { await _host.RunAsync(); }); } catch { _logger.LogError($"http服务主机启动失败,监听地址:{endPoint}。 "); } }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var settings = new CefSettings { CachePath = Path.Combine(Path.GetDirectoryName(typeof(App).Assembly.Location), "cache") }; Cef.Initialize(settings); _ = Task.Run(async() => { var builder = new WebHostBuilder(); builder.ConfigureServices(services => { var server = new OwinServer(); server.UseOwin(appFunc => { var requestContext = Cef.GetGlobalRequestContext(); requestContext.RegisterOwinSchemeHandlerFactory("https", "cefsharp.test", appFunc); }); services.AddSingleton <IServer>(server); }); _host = builder .UseStartup <Startup>() .UseContentRoot(Directory.GetCurrentDirectory()) .Build(); await _host.RunAsync(); }); }
protected override void StartCore(CancellationToken cancellationToken) { new Thread(() => { IWebHost host = null; try { host = _HostBuilder(); host.RunAsync(cancellationToken).GetAwaiter().GetResult(); } catch (Exception ex) { if (!cancellationToken.IsCancellationRequested) { Logs.Tumbler.LogCritical(1, ex, "Error while starting the host"); } } finally { try { if (host != null) { host.Dispose(); } } catch { } } Stopped(); }).Start(); }
public override async Task RunAsync() { PreRunConditions(); Utilities.PrintLogo(); var settings = SelfHostWebHostSettingsFactory.Create(Environment.CurrentDirectory); (var baseAddress, var certificate) = Setup(); IWebHost host = await BuildWebHost(settings, baseAddress, certificate); var runTask = host.RunAsync(); var manager = host.Services.GetRequiredService <WebScriptHostManager>(); await manager.DelayUntilHostReady(); ColoredConsole.WriteLine($"Listening on {baseAddress}"); ColoredConsole.WriteLine("Hit CTRL-C to exit..."); DisplayHttpFunctionsInfo(manager, baseAddress); DisplayDisabledFunctions(manager); await SetupDebuggerAsync(baseAddress); await runTask; }
public static async Task <int> Main(string[] args) { Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration).CreateLogger(); try { Log.Information("Starting API, hold on to your hats!"); IWebHost host = BuildWebHost(args); await host.RunAsync().AnyContext(); return(0); } catch (Exception e) { if (!(e is LoggedException)) { Log.Fatal(e, "{Class} -> {Method} -> API terminated unexpectedly", nameof(Program), nameof(Main)); } return(1); } finally { Log.CloseAndFlush(); } }
public static async Task <int> Main(string[] args) { Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration).CreateLogger(); try { Log.Information("Starting API; Version: {Version}; Build Date: {BuildDate}", VersionInfo.Version, VersionInfo.BuildDate); IWebHost host = BuildWebHost(args); await host.RunAsync().AnyContext(); return(0); } catch (Exception e) { if (!(e is LoggedException)) { Log.Fatal(e, "API terminated unexpectedly"); } return(1); } finally { Log.CloseAndFlush(); } }
private void StartServers() { try { var appLifetime = (IApplicationLifetime)_host.Services.GetService(typeof(IApplicationLifetime)); appLifetime.ApplicationStarted.Register(() => IsStarted = true); #if NETSTANDARD1_3 _logger.Info("WireMock.Net server using netstandard1.3"); #elif NETSTANDARD2_0 _logger.Info("WireMock.Net server using netstandard2.0"); #elif NET46 _logger.Info("WireMock.Net server using .net 4.6.1 or higher"); #endif #if NETSTANDARD1_3 _host.Run(_cts.Token); #else _host.RunAsync(_cts.Token).Wait(); #endif } catch (Exception e) { _runningException = e; _logger.Error(e.ToString()); } finally { IsStarted = false; } }
public static void StartServer(TestContext testContext) { _host = new WebHostBuilder() .UseKestrel() .UseUrls("http://127.0.0.1:0") .UseStartup <Startup>() .Build(); var task = _host.RunAsync(); while (true) { if (_host != null) { if (task.IsFaulted && task.Exception != null) { throw task.Exception; } if (!task.IsCompleted || !task.IsCanceled) { if (!_host.ServerFeatures.Get <IServerAddressesFeature>().Addresses.First().EndsWith(":0")) { break; } } } Thread.Sleep(2000); } }
/// <summary> /// Start the engine and use given router to handle request. /// </summary> /// <param name="router">The router which will handle the request.</param> public override async void Start(IJsonRpcRouter router) { _router = router; var builder = new WebHostBuilder() .SuppressStatusMessages(true) .UseKestrel(options => { options.Listen(_address, _port); }) .ConfigureLogging((_, logging) => { logging.ClearProviders(); }) .Configure(app => { app.Run(context => { var jsonRpcHttpContext = new JsonRpcKestrelHttpContext(context); return(HandleContextAsync(jsonRpcHttpContext, _router)); }); }); _host = builder.Build(); await _host.RunAsync().ConfigureAwait(false); }
// todo: also test DataContractSerializer by using Service.svc endpoint // perhaps make two clients in fixture and use theory to iterate through public SampleServiceFixture() { // start service host this.host = new WebHostBuilder() .ConfigureServices(services => { // init SampleService service mock this.sampleServiceMock = new Mock <ISampleService>(); services.AddSingleton <ISampleService>(sampleServiceMock.Object); services.AddMvc(); }) .Configure(appBuilder => { appBuilder.UseSoapEndpoint <ISampleService>("/Service.asmx", new BasicHttpBinding(), SoapSerializer.XmlSerializer); appBuilder.UseMvc(); }) .UseKestrel() .UseUrls($"http://*:{Port}") .UseContentRoot(Directory.GetCurrentDirectory()) .Build(); #pragma warning disable 4014 host.RunAsync(); #pragma warning restore 4014 // make service client var binding = new BasicHttpBinding(); var endpoint = new EndpointAddress(new Uri($"http://localhost:{Port}/Service.asmx")); var channelFactory = new ChannelFactory <ISampleService>(binding, endpoint); this.sampleServiceClient = channelFactory.CreateChannel(); }
/// <summary> /// /// </summary> public void Start() { try { string root = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName; _Host = WebHost.CreateDefaultBuilder() .UseUrls(_Url) .UseContentRoot(root) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); //logging.AddDebug(); }) .UseNLog() .UseStartup <Startup>() .ConfigureServices((ioc) => { _Service.Initialize(ioc); }) .Build(); _Service.Start(); _Host.RunAsync(); } catch (Exception ex) { //NLog: catch setup errors } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) } }
public static async Task Main(string[] args) { IWebHost host = CreateWebHostBuilder(args: args).Build(); using (IServiceScope scope = host.Services.CreateScope()) { IServiceProvider services = scope.ServiceProvider; try { var currentParticipantService = (CurrentParticipantService)services.GetRequiredService <ICurrentParticipantService>(); currentParticipantService.SetNoHttpContext(); PokerTimeDbContext dbContext = services.GetRequiredService <PokerTimeDbContext>(); dbContext.Initialize(); IMediator mediator = services.GetRequiredService <IMediator>(); await mediator.Send(new SeedBaseDataCommand()); } catch (Exception ex) { ILogger logger = scope.ServiceProvider.GetRequiredService <ILoggerFactory>().CreateLogger(nameof(Program)); logger.LogError(ex, "An error occurred while migrating or initializing the database."); } } await host.RunAsync(); }
private async Task MainThreadAsync() { try { Log.Debug("Resolving localhost url"); var hostEntry = Dns.GetHostEntryAsync("localhost").GetResult(); var localhostIp = hostEntry.AddressList.First(addr => addr.AddressFamily == AddressFamily.InterNetwork); var url = $"http://{localhostIp}:0"; _host = new WebHostBuilder() .UseKestrel() .UseUrls(url) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <WebSocketServer>() .ConfigureServices(s => { s.AddSingleton <IWebSocketHandler>(this); }) .Build(); Log.Info("Starting server host on url {0}", url); await _host.RunAsync(_cancellation.Token).ConfigureAwait(false); Log.Info("Web server host stopped"); } catch (Exception ex) { Log.Error(ex, "Web server host terminated with exception"); throw; } }
public Task Run(string[] args) { Console.WriteLine("Hello from ASP.NET Core MVC web application"); var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("hostsettings.json", optional: true) .AddCommandLine(args) .Build(); IWebHostBuilder builder = WebHost .CreateDefaultBuilder(args) .UseConfiguration(config) .UseNLog() //.Configure(app => //{ // app.Run(context => // context.Response.WriteAsync("Hello, World!")); //}); ; IWebHost runner = builder.UseStartup <AspNetMvcApplicationStartup>().Build(); return(runner.RunAsync()); } // public void Run(string[] args)
/// <summary> /// Defines the entry point of the application. /// </summary> /// <param name="args">The arguments.</param> public static async Task Main(string[] args) { workingDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); Directory.SetCurrentDirectory(workingDirectory); IWebHost builder = CreateWebHostBuilder(args).Build(); var entryAssembly = Assembly.GetEntryAssembly(); var logger = builder.Services.GetService <ILogger <Program> >(); logger.LogInformation($"Week 8 Demo: v{entryAssembly.GetName().Version}"); logger.LogInformation($"Week 8 Demo Working Directory : {Path.GetDirectoryName(entryAssembly.Location)}"); logger.LogInformation($"Operating System: {Environment.OSVersion.Platform} {Environment.OSVersion.VersionString}"); logger.LogInformation($"CLI Version: {Environment.Version}"); logger.LogInformation($"{entryAssembly.GetCustomAttribute<AssemblyCopyrightAttribute>()?.Copyright}"); var personService = builder.Services.GetService <IPersonService>(); // add a demo person await personService.CreatePersonAsync("test", "last name"); // actually start the server implementation await builder.RunAsync(); }
private void StartServers() { try { IsStarted = true; #if NETSTANDARD1_3 _logger.Info("WireMock.Net server using netstandard1.3"); #elif NETSTANDARD2_0 _logger.Info("WireMock.Net server using netstandard2.0"); #elif NET46 _logger.Info("WireMock.Net server using .net 4.6.1 or higher"); #endif #if NETSTANDARD1_3 _host.Run(_cts.Token); #else _host.RunAsync(_cts.Token).Wait(); #endif } catch (Exception e) { _runningException = e; _logger.Error(e.ToString()); } finally { IsStarted = false; } }
public void Start() { _webApiHost = WebHost .CreateDefaultBuilder() .UseUnityServiceProvider(_container) .ConfigureServices(services => { services.AddMvc(); services.AddSwaggerGen(SwaggerDocsConfig); }) .Configure(app => { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseCors(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "DeliveryCompanyIgners V1"); c.RoutePrefix = string.Empty; }); }) .UseUrls("http://*:10500") .Build(); _webApiHost.RunAsync(); }
private static async Task Main(string[] args) { try { _logger.PrintHeader("Telegram bot web service started."); IWebHost webHost = CreateWebHostBuilder(args).Build(); // Set web hook to get messages from Telegram Bot. var serviceSetup = webHost.Services.GetRequiredService <IServiceSetupAsync>(); await serviceSetup.SetWebhookAsync(); // Run the WebHost, and start accepting requests. // There's an async overload, so we may as well use it. await webHost.RunAsync(); await serviceSetup.DeleteWebhookAsync(); } catch (Exception ex) { _logger.Error(ex, $"Exception occurred in {nameof(Main)} method."); } finally { _logger.PrintFooter("Telegram bot web service stopped."); } }
public async Task StartAsync(EndPoint endPoint) { var ipEndPoint = endPoint as IPEndPoint; try { _host = new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel(options => { options.Listen(ipEndPoint); }) .ConfigureLogging((logger) => { logger.AddConfiguration( CPlatform.AppConfig.GetSection("Logging")); }) .Configure(AppResolve) .Build(); await _host.RunAsync(); } catch { _logger.LogError($"http服务主机启动失败,监听地址:{endPoint}。 "); } }
public override async Task RunAsync() { var workerRuntime = WorkerRuntimeLanguageHelper.GetCurrentWorkerRuntimeLanguage(_secretsManager); if (workerRuntime == WorkerRuntime.None) { throw new CliException("your worker runtime is not set. As of 2.0.1-beta.26 a worker runtime setting is required.\n" + $"Please run `func settings add {Constants.FunctionsWorkerRuntime} <option>`\n" + $"Available options: {WorkerRuntimeLanguageHelper.AvailableWorkersRuntimeString}"); } await PreRunConditions(workerRuntime); Utilities.PrintLogo(); var settings = SelfHostWebHostSettingsFactory.Create(Environment.CurrentDirectory); (var baseAddress, var certificate) = Setup(); IWebHost host = await BuildWebHost(settings, workerRuntime, baseAddress, certificate); var runTask = host.RunAsync(); var manager = host.Services.GetRequiredService <WebScriptHostManager>(); await manager.DelayUntilHostReady(); ColoredConsole.WriteLine($"Listening on {baseAddress}"); ColoredConsole.WriteLine("Hit CTRL-C to exit..."); DisplayHttpFunctionsInfo(manager, baseAddress); DisplayDisabledFunctions(manager); await SetupDebuggerAsync(baseAddress); await runTask; }
public override async Task RunAsync() { await PreRunConditions(); Utilities.PrintLogo(); Utilities.PrintVersion(); var settings = SelfHostWebHostSettingsFactory.Create(Environment.CurrentDirectory); (var listenUri, var baseUri, var certificate) = await Setup(); IWebHost host = await BuildWebHost(settings, listenUri, baseUri, certificate); var runTask = host.RunAsync(); var hostService = host.Services.GetRequiredService <WebJobsScriptHostService>(); await hostService.DelayUntilHostReady(); var scriptHost = hostService.Services.GetRequiredService <IScriptJobHost>(); var httpOptions = hostService.Services.GetRequiredService <IOptions <HttpOptions> >(); DisplayHttpFunctionsInfo(scriptHost, httpOptions.Value, baseUri); DisplayDisabledFunctions(scriptHost); await runTask; }
public void RestartServer(Settings settings) { StopServer(settings); if (settings.Enabled == false) { return; } this.server = WebHost.CreateDefaultBuilder().UseKestrel(x => { if (settings.AllowExternalIps) { x.ListenAnyIP(settings.PortNumber); } x.ListenLocalhost(settings.PortNumber); }).UseStartup <ApiStartup>().UseDefaultServiceProvider((b, o) => { }) .Build(); serverStatus = "Starting"; this.messageBusService.Emit("serverstatuschanged", serverStatus); Task.Run(() => { Thread.Sleep(3000); server.RunAsync(); serverStatus = "Started"; this.messageBusService.Emit("serverstatuschanged", serverStatus); }); }
public static void Main(string[] args) { Heartbeat.Instance.InitHeartbeat("Products REST-API"); Heartbeat.Instance.Start(); Messenger.CreateInstance("Products", makeVerbose: true); Messenger.Instance.SetupListener <List <ProductUpdate> >((List <ProductUpdate> updates) => { foreach (ProductUpdate productUpdate in updates) { SQL_Interface.Instance.ReduceItemQuantity(productUpdate); } }, Messenger.MessageType.ProductUpdates); try { IWebHost host = CreateWebHostBuilder(args).Build(); host.RunAsync(); host.WaitForShutdown();; } finally { Messenger.DisposeInstance(); } }
public void Start() { if (_running) { return; } if (_tokenSource != null && _tokenSource.IsCancellationRequested) { return; } _tokenSource = new CancellationTokenSource(); _tokenSource.Token.ThrowIfCancellationRequested(); _running = true; _web = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup <Startup>() .Build(); _web.RunAsync(_tokenSource.Token); }
public static async Task RunWithStartupTasksAsync(this IWebHost webHost, CancellationToken cancellationToken = default, params IStartupTask[] tasks) { using (var scope = webHost.Services.CreateScope()) { // Load all tasks from DI var startupTasks = scope.ServiceProvider.GetServices <IStartupTask>(); var logger = scope.ServiceProvider.GetService <ILogger <Program> >(); if (tasks != null) { startupTasks = startupTasks.Union(tasks); } // Execute all the tasks foreach (var startupTask in startupTasks) { logger.LogInformation($"Startup task started :{startupTask.GetType().Name}"); try { await startupTask.ExecuteAsync(cancellationToken); logger.LogInformation($"Startup task completed:{startupTask.GetType().Name}"); } catch (Exception error) { logger.LogWarning($"Startup task {startupTask.GetType().Name} exit with error: {error.Message}"); throw; } } } // Start the server as normal await webHost.RunAsync(cancellationToken); }
public static int Main(string[] args) { int returnCode = 1; var cancellationToken = new CancellationTokenSource().Token; Console.WriteLine("Starting web host"); IWebHost webHost = BuildWebHost(args); webHost.RunAsync(cancellationToken); try { var requestTask = TestWebRequest(); requestTask.Wait(new TimeSpan(0, 0, RequestTimeOut)); returnCode = requestTask.Result; } catch (Exception e) { // If the server didn't start properly Console.WriteLine("Web request failed"); Console.WriteLine(e.InnerException.ToString()); return(1); } Console.WriteLine("Shutting down web host"); webHost.StopAsync(new TimeSpan(0, 0, RequestTimeOut)); return(returnCode); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development"); _ = Task.Run(async() => { var builder = new WebHostBuilder(); builder.ConfigureServices(services => { var server = new OwinServer(); server.UseOwin(appFunc => { _appFunc = appFunc; }); services.AddSingleton <IServer>(server); services.AddMvc(); }); builder.ConfigureLogging(logging => { logging.AddConsole(); }); _host = builder .UseStartup <Startup>() .UseContentRoot(Directory.GetCurrentDirectory()) .Build(); await _host.RunAsync(); }); }
public WebClientUnitTests() { _hostUrl = "http://localhost:19876"; _token = new CancellationTokenSource(); _host = new WebHostBuilder() .UseKestrel() .ConfigureServices(s => { s.AddMvcCore() .AddMvcOptions(opt => opt.EnableEndpointRouting = false) .AddFormatterMappings() .AddJsonOptions(opt => opt.JsonSerializerOptions.WriteIndented = true); s.AddWebClient <IWebClient, WebClient>(_hostUrl) .AddWebClient <IWebClientClone, WebClientClone>(_hostUrl + "/Test"); }) .Configure(app => { app.UseMvc(); }) .UseUrls(_hostUrl) .Build(); _webClient = _host.Services.GetRequiredService <IWebClient>(); _webClientClone = _host.Services.GetRequiredService <IWebClientClone>(); _hostTask = _host.RunAsync(_token.Token); }