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(); }
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 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(); } }
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); } } } }
private static IApplication CreateWebHost(IConfigurationRoot config) { var webHostBuilder = new WebHostBuilder(config) .UseServer("Microsoft.AspNet.Server.WebListener") .Build(); return webHostBuilder.Start(); }
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(); }
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); } } } }
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) { 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; } }
public static void Main(string[] args) { var host = new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel() .UseStartup<Startup>() .Build(); host.Run(); }
// Entry point for the application. public static void Main(string[] args) { var host = new WebHostBuilder() .UseDefaultConfiguration(args) .UseIISPlatformHandlerUrl() .UseStartup<Startup>() .Build(); host.Run(); }
public static void Main(string[] args) { var host = new WebHostBuilder() .UseDefaultConfiguration(args) .UseIISPlatformHandlerUrl() .UseServer("Microsoft.AspNet.Server.Kestrel") .UseStartup<Startup>() .Build(); host.Run(); }
public static void Main(string[] args) { var host = new WebHostBuilder() .UseDefaultConfiguration(args) .UseServer("Microsoft.AspNet.Server.Kestrel") .UseApplicationBasePath(Directory.GetCurrentDirectory()) .UseStartup<Startup>() .Build(); host.Run(); }
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); } } } }
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); }
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 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)); } } }
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(); }
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; }
public async void SpringCloudConfigServer_ReturnsExpectedDefaultData_AsInjectedOptions() { // Arrange var builder = new WebHostBuilder().UseStartup<TestServerStartup>(); // Act and Assert (TestServer expects Spring Cloud Config server to be running) using (var server = new TestServer(builder)) { var client = server.CreateClient(); string result = await client.GetStringAsync("http://localhost/Home/VerifyAsInjectedOptions"); Assert.Equal("spam" + "bar"+ "Spring Cloud Samples" + "https://github.com/spring-cloud-samples", result); } }
//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 async Task DoesNotModifyCacheHeaders_WhenNoExceptionIsThrown() { var expiresTime = DateTime.UtcNow.AddDays(10).ToString("R"); var expectedResponseBody = "Hello world!"; var builder = new WebHostBuilder() .UseStartup(app => { var transformations = new TransformationCollectionBuilder() .Return(404) .For<Exception>() .Transformations; var options = new ExceptionTransformationOptions(transformations); app.UseExceptionTransformations(options); app.Run(async (httpContext) => { httpContext.Response.Headers.Add("Cache-Control", new[] { "max-age=3600" }); httpContext.Response.Headers.Add("Pragma", new[] { "max-age=3600" }); httpContext.Response.Headers.Add("Expires", new[] { expiresTime }); httpContext.Response.Headers.Add("ETag", new[] { "abcdef" }); await httpContext.Response.WriteAsync(expectedResponseBody); }); }); using (var server = new TestServer(builder)) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); response.EnsureSuccessStatusCode(); Assert.Equal(expectedResponseBody, await response.Content.ReadAsStringAsync()); IEnumerable<string> values; Assert.True(response.Headers.TryGetValues("Cache-Control", out values)); Assert.Single(values); Assert.Equal("max-age=3600", values.First()); Assert.True(response.Headers.TryGetValues("Pragma", out values)); Assert.Single(values); Assert.Equal("max-age=3600", values.First()); Assert.True(response.Content.Headers.TryGetValues("Expires", out values)); Assert.Single(values); Assert.Equal(expiresTime, values.First()); Assert.True(response.Headers.TryGetValues("ETag", out values)); Assert.Single(values); Assert.Equal("abcdef", values.First()); } }
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(); }
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"); }
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(); }
public static void Main(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); Settings.Initialize().Wait(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup <Startup>() .UseUrls("http://*:" + Settings.Instance.HttpPort) .Build(); host.Run(); }
private TestServer CreateServer( Action <IBankIdBuilder> configureBankId, Action <IApplicationBuilder> configureApplication, Action <IServiceCollection> configureServices = null) { var webHostBuilder = new WebHostBuilder() .UseSolutionRelativeContentRoot(Path.Combine("test", "ActiveLogin.Authentication.BankId.AspNetCore.Test")) .Configure(app => { configureApplication.Invoke(app); }) .ConfigureServices(services => { services.AddAuthentication().AddBankId(configureBankId); services.AddMvc(); configureServices?.Invoke(services); }); return(new TestServer(webHostBuilder)); }
public async Task CustomCorrelationHeader() { const string headerName = "Correlate-This"; var builder = new WebHostBuilder() .ConfigureServices(service => service.AddCorrelation(headerName)) .Configure(app => app.UseCorrelation()); using var server = new TestServer(builder); var response = await server.CreateClient().GetAsync(""); var hasHeader = response.Headers.TryGetValues(headerName, out var header); Assert.True(hasHeader); var correlation = new Guid(header.First()); Assert.NotEqual(Guid.Empty, correlation); }
public async Task Logging_Labels() { string testId = IdGenerator.FromDateTime(); DateTime startTime = DateTime.UtcNow; var builder = new WebHostBuilder().UseStartup <WarningWithLabelsLoggerTestApplication>(); using (var server = new TestServer(builder)) using (var client = server.CreateClient()) { await client.GetAsync($"/Main/Warning/{testId}"); var results = _polling.GetEntries(startTime, testId, 1, LogSeverity.Warning); var entry = results.Single(); Assert.Equal(3, entry.Labels.Count); Assert.Equal("some-value", entry.Labels["some-key"]); Assert.Equal("Hello, World!", entry.Labels["Foo"]); Assert.NotEmpty(entry.Labels["trace_identifier"]); } }
public async Task SendAsync_Default_Protocol11() { // Arrange var expected = "GET Response"; RequestDelegate appDelegate = ctx => ctx.Response.WriteAsync(expected); var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate)); var server = new TestServer(builder); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:12345"); // Act var message = await client.SendAsync(request); var actual = await message.Content.ReadAsStringAsync(); // Assert Assert.Equal(expected, actual); Assert.Equal(new Version(1, 1), message.Version); }
public async Task Logging_Trace() { string traceId = "105445aa7843bc8bf206b12000100f00"; string testId = Utils.GetTestId(); DateTime startTime = DateTime.UtcNow; var builder = new WebHostBuilder().UseStartup <NoBufferWarningLoggerTestApplication>(); using (var server = new TestServer(builder)) using (var client = server.CreateClient()) { client.DefaultRequestHeaders.Add(TraceHeaderContext.TraceHeader, TraceHeaderContext.Create(traceId, 81237123, null).ToString()); await client.GetAsync($"/Main/Critical/{testId}"); var results = _polling.GetEntries(startTime, testId, 1, LogSeverity.Critical); Assert.Contains(Utils.GetProjectIdFromEnvironment(), results.Single().Trace); Assert.Contains(traceId, results.Single().Trace); } }
public async void CloudFoundryEndpointMiddleware_ServiceContractNotBroken() { // arrange a server and client var builder = new WebHostBuilder() .UseStartup <Startup>() .ConfigureAppConfiguration((builderContext, config) => config.AddInMemoryCollection(appSettings)); using (var server = new TestServer(builder)) { var client = server.CreateClient(); // send the request var result = await client.GetAsync("http://localhost/cloudfoundryapplication"); var json = await result.Content.ReadAsStringAsync(); // assert Assert.Equal("{\"type\":\"steeltoe\",\"_links\":{\"info\":{\"href\":\"http://localhost/cloudfoundryapplication/info\",\"templated\":false},\"self\":{\"href\":\"http://localhost/cloudfoundryapplication\",\"templated\":false}}}", json); } }
// Entry point for the application. public static void Main(string[] args) { _config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .AddCommandLine(args) .Build(); var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) // for the cert file .ConfigureLogging(factory => { factory.SetMinimumLevel(LogLevel.Debug); factory.AddConsole(); }) .UseStartup <Startup>() .Build(); host.Run(); }
public async Task SingleTrailingSlash_NoPathBase() { // Arrange var expected = "GET Response"; RequestDelegate appDelegate = ctx => { Assert.Equal("", ctx.Request.PathBase.Value); Assert.Equal("/", ctx.Request.Path.Value); return(ctx.Response.WriteAsync(expected)); }; var builder = new WebHostBuilder().Configure(app => app.Run(appDelegate)); var server = new TestServer(builder); var client = server.CreateClient(); // Act var actual = await client.GetStringAsync("http://localhost:12345/"); // Assert Assert.Equal(expected, actual); }
public async Task ExistingRequestServicesWillNotBeReplaced() { var builder = new WebHostBuilder().Configure(app => { app.Run(context => { var service = context.RequestServices.GetService <TestService>(); return(context.Response.WriteAsync("Found:" + (service != null))); }); }) .ConfigureServices(services => { services.AddTransient <IStartupFilter, RequestServicesFilter>(); }); var server = new TestServer(builder); string result = await server.CreateClient().GetStringAsync("/path"); Assert.Equal("Found:True", result); }
public static void Main(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("hosting.json", optional: true) .AddInMemoryCollection(defaults) .AddEnvironmentVariables("ASPNETCORE_ENVIRONMENT") .AddCommandLine(args) .Build(); var host = new WebHostBuilder() .UseConfiguration(configuration) .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel() .UseIISIntegration() .UseStartup <Startup>() .Build(); host.Run(); }
public static IWebHost BuildWebHost(string[] args) { IWebHostBuilder builder = new WebHostBuilder(); //注入WebHostBuilder return(builder.ConfigureServices(service => { service.AddSingleton(builder); }) //加载configuration配置文件 .ConfigureAppConfiguration(conbuilder => { conbuilder.AddJsonFile("configuration.json"); }) .UseKestrel() .UseUrls("http://*:5000") .UseStartup <Startup>() .Build()); }
public void register_inmemory() { var hostBuilder = new WebHostBuilder() .ConfigureAppConfiguration(config => { config.Sources.Clear(); config.AddInMemoryCollection(new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("storage_provider", StorageProviderEnum.InMemory.ToString()) }); }) .UseStartup <Startup>(); var host = hostBuilder.Build(); var context = host.Services.GetRequiredService <HealthChecksDb>(); context.Database.ProviderName.Should().Be(InMemoryProviderName); }
public virtual async void TestByUserUserIdFound() { var builder = new WebHostBuilder() .UseEnvironment("Production") .UseStartup <TestStartup>(); TestServer testServer = new TestServer(builder); var client = new ApiClient(testServer.CreateClient()); client.SetBearerToken(JWTTestHelper.GenerateBearerToken()); List <ApiTweetClientResponseModel> response = await client.ByTweetByUserUserId(1); response.Should().NotBeEmpty(); response[0].Content.Should().Be("A"); response[0].Date.Should().Be(DateTime.Parse("1/1/1987 12:00:00 AM")); response[0].LocationId.Should().Be(1); response[0].Time.Should().Be(TimeSpan.Parse("01:00:00")); response[0].TweetId.Should().Be(1); response[0].UserUserId.Should().Be(1); }
internal static IWebHost CreateDynamicHost(string basePath, out string root, out string baseAddress, Action <AzureRelayOptions> configureOptions, RequestDelegate app, TokenProvider tp = null) { var prefix = UrlPrefix.Create(new Uri(new Uri(Utilities.GetRelayUrl()), basePath).AbsoluteUri, tp); root = prefix.FullPrefix; baseAddress = prefix.ToString(); var builder = new WebHostBuilder() .UseAzureRelay(options => { options.UrlPrefixes.Add(prefix); configureOptions(options); }) .Configure(appBuilder => appBuilder.Run(app)); var host = builder.Build(); host.Start(); return(host); }
public async Task Run(CancellationToken cancellationToken) { var config = new ConfigurationBuilder() .AddEnvironmentVariables(prefix: "ASPNETCORE_") .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseUrls("http://localhost:9090") .UseContentRoot(Directory.GetCurrentDirectory()) .ConfigureServices(services => { services.AddTransient(w => _asyncProcessor); }) .UseStartup <Startup>() .ConfigureLogging((ctx, logging) => ConfigureLogging(logging)) .Build(); await host.RunAsync(cancellationToken); }
/// <summary> /// Setup a IWebHost in the mocks. This will use the configuration files from the test project. /// </summary> /// <param name="mockup">The mockup class to configure.</param> /// <returns>The passed in mockup test.</returns> public static Mockup SetupWebHost(this Mockup mockup) { mockup.Add <IWebHost>(m => { var hostBuilder = new WebHostBuilder() .UseEnvironment("development") .UseKestrel() .UseStartup <Startup>() .ConfigureAppConfiguration(configuration => { configuration.Sources.Clear(); configuration.AddJsonFile("appsettings.json"); configuration.AddJsonFile("appsettings.Development.json"); }); return(hostBuilder.Build()); }); return(mockup); }
public async Task CallingAbortInsideHandlerShouldSetRequestAborted() { var requestAborted = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously); var builder = new WebHostBuilder() .Configure(app => { app.Run(context => { context.RequestAborted.Register(() => requestAborted.SetResult(0)); context.Abort(); return(Task.CompletedTask); }); }); var server = new TestServer(builder); var ex = await Assert.ThrowsAsync <Exception>(() => server.SendAsync(c => { })); Assert.Equal("The application aborted the request.", ex.Message); await requestAborted.Task.DefaultTimeout(); }
public static IWebHost BuildWebHost(string[] args) { var rootFolder = Directory.GetParent(Directory.GetCurrentDirectory()); var dirs = Directory.GetDirectories(rootFolder.FullName, "config"); DirectoryInfo configDir = new DirectoryInfo(dirs[0]); var config = new ConfigurationBuilder() .SetBasePath(configDir.FullName) .AddJsonFile("frontend_config.json", optional: true) .Build(); var host = new WebHostBuilder() .UseKestrel() .UseConfiguration(config) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>() .Build(); return(host); }
protected AcceptanceTestsBase(ITestOutputHelper outputHelper) { OutputHelper = outputHelper; UpstreamBuilder = new WebHostBuilder() .UseStartup <UpstreamStartup>() .ConfigureLogging(builder => { builder.AddProvider(new XunitLoggerProvider(OutputHelper, "Upstream")); builder.SetMinimumLevel(LogLevel.Debug); }); ProxyBuilder = new WebHostBuilder() .UseStartup <ProxyStartup>() .ConfigureLogging(builder => { builder.AddProvider(new XunitLoggerProvider(OutputHelper, "Proxy")); builder.SetMinimumLevel(LogLevel.Debug); }); }
public KestrellTestServer(WebHostBuilder builder = null) { if (builder == null) { var hostBuilder = new WebHostBuilder() .UseKestrel() .UseUrls("http://127.0.0.1:0/") .ConfigureServices(services => { services.AddDistributedMemoryCache(); services.AddSession(options => { // Set a long timeout for easy testing. options.IdleTimeout = TimeSpan.FromDays(10); options.Cookie.HttpOnly = true; });; }); this.builder = hostBuilder; } }
public async Task CanAccessHttpContext() { var builder = new WebHostBuilder().Configure(app => { app.Run(context => { var accessor = app.ApplicationServices.GetRequiredService <IHttpContextAccessor>(); return(context.Response.WriteAsync("HasContext:" + (accessor.HttpContext != null))); }); }) .ConfigureServices(services => { services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); }); var server = new TestServer(builder); string result = await server.CreateClient().GetStringAsync("/path"); Assert.Equal("HasContext:True", result); }
public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .ConfigureAppConfiguration((context, configBuilder) => { configBuilder .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); }) .ConfigureLogging(loggerFactory => loggerFactory .AddConsole() .AddDebug()) .UseStartup <Startup>() .Build(); host.Run(); }
public static TestServer Create <TStartup>(IServiceCollection replacementServices, string contentRoot) where TStartup : class { if (replacementServices == null) { throw new ArgumentNullException(nameof(replacementServices)); } if (contentRoot == null) { throw new ArgumentNullException(nameof(contentRoot)); } var hostBuilder = new WebHostBuilder() .UseContentRoot(contentRoot) .ConfigureServices(cs => cs.AddSingleton(new ServiceReplacer(replacementServices))) .UseStartup <TStartup>(); var testServer = new TestServer(hostBuilder); return(testServer); }
public async Task FlushSendsHeaders() { var block = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously); var builder = new WebHostBuilder().Configure(app => { app.Run(async c => { c.Response.Headers["TestHeader"] = "TestValue"; await c.Response.Body.FlushAsync(); await block.Task; await c.Response.WriteAsync("BodyFinished"); }); }); var server = new TestServer(builder); var context = await server.SendAsync(c => { }); Assert.Equal("TestValue", context.Response.Headers["TestHeader"]); block.SetResult(0); Assert.Equal("BodyFinished", new StreamReader(context.Response.Body).ReadToEnd()); }
public void TestMethod1() { var apiWebHostBuilder = new WebHostBuilder() .UseEnvironment("Testing") .UseStartup <Startup>(); var apiTestServer = new TestServer(apiWebHostBuilder); _apiDbContext = apiTestServer.Host.Services.GetService(typeof(NiisWebContext)) as NiisWebContext; _apiHttpClient = apiTestServer.CreateClient(); var portalWebHostBuilder = new WebHostBuilder() .UseEnvironment("Testing"); //.UseStartup<Portal.Startup>()ж var portalTestServer = new TestServer(portalWebHostBuilder); _portalDbContext = portalTestServer.Host.Services.GetService(typeof(NiisWebContext)) as NiisWebContext; _portalHttpClient = portalTestServer.CreateClient(); }
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 string StartHosting(int?port) { // If the port was not specified, we pass in 0, in which case ASP.NET picks a random free port. var hostingPort = port ?? 0; var hostBuilder = new WebHostBuilder() .UseKestrel() .UseUrls($"http://127.0.0.1:{hostingPort}/") .ConfigureServices(startup.ConfigureServices) .Configure(startup.Configure); webHost = hostBuilder.Build(); webHost.Start(); appLifetime = webHost.Services.GetRequiredService <IApplicationLifetime>(); var serverAddresses = webHost.ServerFeatures.Get <IServerAddressesFeature>(); return(serverAddresses.Addresses.First(it => Uri.IsWellFormedUriString(it, UriKind.Absolute))); }
public async Task WillReplaceServiceProviderFeatureWithNullRequestServices() { var builder = new WebHostBuilder().Configure(app => { app.Run(context => { Assert.Null(context.RequestServices); return(context.Response.WriteAsync("Success")); }); }) .ConfigureServices(services => { services.AddTransient <IStartupFilter, NullServiceProvidersFeatureFilter>(); }); var server = new TestServer(builder); var result = await server.CreateClient().GetStringAsync("/path"); Assert.Equal("Success", result); }
public async Task SettingPathBase() { var options = new RewriteOptions().AddRedirect("(.*)", "$1"); var builder = new WebHostBuilder() .Configure(app => { app.UseRewriter(options); app.Run(context => context.Response.WriteAsync( context.Request.Path + context.Request.QueryString)); }); var server = new TestServer(builder) { BaseAddress = new Uri("http://localhost:5000/foo") }; var response = await server.CreateClient().GetAsync(""); Assert.Equal("/foo", response.Headers.Location.OriginalString); }
public async Task CheckRewritePath() { var options = new RewriteOptions().AddRewrite("(.*)", "http://example.com/$1", skipRemainingRules: false); var builder = new WebHostBuilder() .Configure(app => { app.UseRewriter(options); app.Run(context => context.Response.WriteAsync( context.Request.Scheme + "://" + context.Request.Host + context.Request.Path + context.Request.QueryString)); }); var server = new TestServer(builder); var response = await server.CreateClient().GetStringAsync("foo"); Assert.Equal("http://example.com/foo", response); }
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); } } } }
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(); }
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(); }
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; }