diff --git a/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs b/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs index 4b53a43a5be1..bf4848307a41 100644 --- a/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs +++ b/src/Middleware/CORS/test/UnitTests/CorsMiddlewareTests.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; @@ -27,20 +28,27 @@ public class CorsMiddlewareTests public async Task CorsRequest_MatchesPolicy_OnCaseInsensitiveAccessControlRequestMethod(string accessControlRequestMethod) { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT")); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT")); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Actual request. @@ -60,22 +68,29 @@ public async Task CorsRequest_MatchesPolicy_OnCaseInsensitiveAccessControlReques public async Task CorsRequest_MatchPolicy_SetsResponseHeaders() { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader")); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader")); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Actual request. @@ -102,24 +117,31 @@ public async Task PreFlight_MatchesPolicy_OnCaseInsensitiveOptionsMethod(string policy.Origins.Add(OriginUrl); policy.Methods.Add("PUT"); - var hostBuilder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors("customPolicy"); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => - { - services.AddCors(options => + app.UseCors("customPolicy"); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => { - options.AddPolicy("customPolicy", policy); + services.AddCors(options => + { + options.AddPolicy("customPolicy", policy); + }); }); - }); + }).Build(); - using (var server = new TestServer(hostBuilder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { // Act // Preflight request. @@ -144,24 +166,31 @@ public async Task PreFlight_MatchesPolicy_SetsResponseHeaders() policy.Headers.Add("Header1"); policy.ExposedHeaders.Add("AllowedHeader"); - var hostBuilder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors("customPolicy"); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => - { - services.AddCors(options => + app.UseCors("customPolicy"); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => { - options.AddPolicy("customPolicy", policy); + services.AddCors(options => + { + options.AddPolicy("customPolicy", policy); + }); }); - }); + }).Build(); - using (var server = new TestServer(hostBuilder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { // Act // Preflight request. @@ -202,24 +231,31 @@ public async Task PreFlight_WithCredentialsAllowed_ReflectsRequestHeaders() .AllowCredentials() .Build(); - var hostBuilder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors("customPolicy"); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => - { - services.AddCors(options => + app.UseCors("customPolicy"); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => { - options.AddPolicy("customPolicy", policy); + services.AddCors(options => + { + options.AddPolicy("customPolicy", policy); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Preflight request. @@ -260,22 +296,29 @@ public async Task PreFlight_WithCredentialsAllowed_ReflectsRequestHeaders() public async Task PreFlightRequest_DoesNotMatchPolicy_SetsResponseHeadersAndReturnsNoContent() { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader")); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader")); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Preflight request. @@ -288,28 +331,37 @@ public async Task PreFlightRequest_DoesNotMatchPolicy_SetsResponseHeadersAndRetu Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Empty(response.Headers); } + + await host.StartAsync(); } [Fact] public async Task CorsRequest_DoesNotMatchPolicy_DoesNotSetHeaders() { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader")); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader")); + app.Run(async context => + { + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); - using (var server = new TestServer(hostBuilder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { // Act // Actual request. @@ -387,38 +439,45 @@ public async Task DoesNotSetHeaders_ForNoPolicy() public async Task PreFlight_MatchesDefaultPolicy_SetsResponseHeaders() { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => - { - services.AddCors(options => - { - options.AddDefaultPolicy(policyBuilder => + app.UseCors(); + app.Run(async context => { - policyBuilder - .WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader") - .Build(); + await context.Response.WriteAsync("Cross origin response"); }); - options.AddPolicy("policy2", policyBuilder => + }) + .ConfigureServices(services => + { + services.AddCors(options => { - policyBuilder - .WithOrigins("http://test.example.com") - .Build(); + options.AddDefaultPolicy(policyBuilder => + { + policyBuilder + .WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader") + .Build(); + }); + options.AddPolicy("policy2", policyBuilder => + { + policyBuilder + .WithOrigins("http://test.example.com") + .Build(); + }); }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Preflight request. @@ -453,23 +512,30 @@ public async Task PreFlight_MatchesDefaultPolicy_SetsResponseHeaders() public async Task CorsRequest_SetsResponseHeaders() { // Arrange - var hostBuilder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader")); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - context.Response.Headers.Add("Test", "Should-Appear"); - await context.Response.WriteAsync("Cross origin response"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader")); + app.Run(async context => + { + context.Response.Headers.Add("Test", "Should-Appear"); + await context.Response.WriteAsync("Cross origin response"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Actual request. @@ -506,39 +572,46 @@ public async Task CorsRequest_SetsResponseHeader_IfExceptionHandlerClearsRespons { // Arrange var exceptionSeen = true; - var hostBuilder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - // Simulate ExceptionHandler middleware - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - try - { - await next(); - } - catch (Exception) + // Simulate ExceptionHandler middleware + app.Use(async (context, next) => { - exceptionSeen = true; - context.Response.Clear(); - context.Response.StatusCode = 500; - } - }); + try + { + await next(); + } + catch (Exception) + { + exceptionSeen = true; + context.Response.Clear(); + context.Response.StatusCode = 500; + } + }); - app.UseCors(builder => - builder.WithOrigins(OriginUrl) - .WithMethods("PUT") - .WithHeaders("Header1") - .WithExposedHeaders("AllowedHeader")); + app.UseCors(builder => + builder.WithOrigins(OriginUrl) + .WithMethods("PUT") + .WithHeaders("Header1") + .WithExposedHeaders("AllowedHeader")); - app.Run(context => - { - context.Response.Headers.Add("Test", "Should-Not-Exist"); - throw new Exception("Runtime error"); - }); - }) - .ConfigureServices(services => services.AddCors()); + app.Run(context => + { + context.Response.Headers.Add("Test", "Should-Not-Exist"); + throw new Exception("Runtime error"); + }); + }) + .ConfigureServices(services => services.AddCors()); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(hostBuilder)) + using (var server = host.GetTestServer()) { // Act // Actual request. diff --git a/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/Startup.cs b/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/Startup.cs index 3043f59bcd98..3baa298e1189 100644 --- a/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/Startup.cs +++ b/src/Middleware/CORS/test/testassets/CorsMiddlewareWebSite/Startup.cs @@ -1,9 +1,11 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace CorsMiddlewareWebSite { @@ -19,15 +21,19 @@ public void Configure(IApplicationBuilder app) app.UseCors(policy => policy.WithOrigins("http://example.com")); app.UseMiddleware(); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } -} \ No newline at end of file +} diff --git a/src/Middleware/ConcurrencyLimiter/sample/Startup.cs b/src/Middleware/ConcurrencyLimiter/sample/Startup.cs index bd4bf2ec58a8..72d38f94f619 100644 --- a/src/Middleware/ConcurrencyLimiter/sample/Startup.cs +++ b/src/Middleware/ConcurrencyLimiter/sample/Startup.cs @@ -17,7 +17,7 @@ public void ConfigureServices(IServiceCollection services) { services.AddStackPolicy(options => { - options.MaxConcurrentRequests = 2; + options.MaxConcurrentRequests = 2; options.RequestQueueLimit = 25; }); } @@ -33,13 +33,17 @@ public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - new WebHostBuilder() - .UseKestrel() - .UseStartup() + return new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseStartup(); + }) .Build() - .Run(); + .RunAsync(); } } } diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs index 630c34e7cf82..2acd8258ad20 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/DatabaseErrorPageMiddlewareTest.cs @@ -17,6 +17,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Xunit; @@ -27,10 +28,19 @@ public class DatabaseErrorPageMiddlewareTest [Fact] public async Task Successful_requests_pass_thru() { - var builder = new WebHostBuilder().Configure(app => app - .UseDatabaseErrorPage() - .UseMiddleware()); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => app + .UseDatabaseErrorPage() + .UseMiddleware()); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); @@ -53,10 +63,19 @@ public virtual async Task Invoke(HttpContext context) [Fact] public async Task Non_database_exceptions_pass_thru() { - var builder = new WebHostBuilder().Configure(app => app - .UseDatabaseErrorPage() - .UseMiddleware()); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => app + .UseDatabaseErrorPage() + .UseMiddleware()); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var ex = await Assert.ThrowsAsync(async () => await server.CreateClient().GetAsync("http://localhost/")); @@ -82,7 +101,8 @@ public async Task Existing_database_not_using_migrations_exception_passes_thru() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); var ex = await Assert.ThrowsAsync(async () => await server.CreateClient().GetAsync("http://localhost/")); @@ -114,7 +134,8 @@ public async Task Error_page_displayed_no_migrations() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -142,13 +163,13 @@ public virtual Task Invoke(HttpContext context) [ConditionalFact] [OSSkipCondition(OperatingSystems.Linux)] [OSSkipCondition(OperatingSystems.MacOSX)] - public void No_exception_on_diagnostic_event_received_when_null_state() + public async Task No_exception_on_diagnostic_event_received_when_null_state() { using (var database = SqlTestStore.CreateScratch()) { - using (var server = SetupTestServer(database)) + using (var server = await SetupServer(database)) { - using (var db = server.Host.Services.GetService()) + using (var db = server.Services.GetService()) { db.Blogs.Add(new Blog()); @@ -172,7 +193,8 @@ public async Task Error_page_displayed_pending_migrations() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -208,7 +230,8 @@ public async Task Error_page_displayed_pending_model_changes() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -245,7 +268,8 @@ public async Task Error_page_then_apply_migrations() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); var client = server.CreateClient(); var expectedMigrationsEndpoint = "/ApplyDatabaseMigrations"; @@ -302,7 +326,11 @@ public async Task Customize_migrations_end_point() using (var database = SqlTestStore.CreateScratch()) { - var builder = new WebHostBuilder() + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() .Configure(app => { app.UseDatabaseErrorPage(new DatabaseErrorPageOptions @@ -317,7 +345,11 @@ public async Task Customize_migrations_end_point() services.AddDbContext( optionsBuilder => optionsBuilder.UseSqlite(database.ConnectionString)); }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); @@ -335,16 +367,24 @@ public async Task Pass_thru_when_context_not_in_services() { var logProvider = new TestLoggerProvider(); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseDatabaseErrorPage(); - app.UseMiddleware(); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseDatabaseErrorPage(); + app.UseMiddleware(); #pragma warning disable CS0618 // Type or member is obsolete - app.ApplicationServices.GetService().AddProvider(logProvider); + app.ApplicationServices.GetService().AddProvider(logProvider); #pragma warning restore CS0618 // Type or member is obsolete - }); - var server = new TestServer(builder); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); try { @@ -391,7 +431,8 @@ public async Task Pass_thru_when_exception_in_logic() { var logProvider = new TestLoggerProvider(); - var server = SetupTestServer(database, logProvider); + using var host = await SetupServer(database, logProvider); + using var server = host.GetTestServer(); try { @@ -430,7 +471,8 @@ public async Task Error_page_displayed_when_exception_wrapped() { using (var database = SqlTestStore.CreateScratch()) { - TestServer server = SetupTestServer(database); + using var host = await SetupServer(database); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); @@ -461,29 +503,36 @@ public virtual Task Invoke(HttpContext context) } } - private static TestServer SetupTestServer(SqlTestStore database, ILoggerProvider logProvider = null) + private static async Task SetupServer(SqlTestStore database, ILoggerProvider logProvider = null) where TContext : DbContext { - var builder = new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseDatabaseErrorPage(); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseDatabaseErrorPage(); - app.UseMiddleware(); + app.UseMiddleware(); - if (logProvider != null) - { + if (logProvider != null) + { #pragma warning disable CS0618 // Type or member is obsolete - app.ApplicationServices.GetService().AddProvider(logProvider); + app.ApplicationServices.GetService().AddProvider(logProvider); #pragma warning restore CS0618 // Type or member is obsolete - } - }) - .ConfigureServices(services => - { - services.AddDbContext(optionsBuilder => optionsBuilder.UseSqlite(database.ConnectionString)); - }); + } + }) + .ConfigureServices(services => + { + services.AddDbContext(optionsBuilder => optionsBuilder.UseSqlite(database.ConnectionString)); + }); + }).Build(); + + await host.StartAsync(); - return new TestServer(builder); + return host; } private static UrlEncoder _urlEncoder = UrlEncoder.Default; diff --git a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs index d77826fda4a6..ba93e736d722 100644 --- a/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs +++ b/src/Middleware/Diagnostics.EntityFrameworkCore/test/FunctionalTests/MigrationsEndPointMiddlewareTest.cs @@ -18,6 +18,7 @@ using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.Tests @@ -27,10 +28,19 @@ public class MigrationsEndPointMiddlewareTest [Fact] public async Task Non_migration_requests_pass_thru() { - var builder = new WebHostBuilder().Configure(app => app - .UseMigrationsEndPoint() - .UseMiddleware()); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => app + .UseMigrationsEndPoint() + .UseMiddleware()); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/"); @@ -75,7 +85,11 @@ private async Task Migration_request(bool useCustomPath) var path = useCustomPath ? new PathString("/EndPoints/ApplyMyMigrations") : MigrationsEndPointOptions.DefaultPath; - var builder = new WebHostBuilder() + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() .Configure(app => { if (useCustomPath) @@ -97,7 +111,11 @@ private async Task Migration_request(bool useCustomPath) options.UseSqlite(database.ConnectionString); }); }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); using (var db = BloggingContextWithMigrations.CreateWithoutExternalServiceProvider(optionsBuilder.Options)) { @@ -128,12 +146,20 @@ private async Task Migration_request(bool useCustomPath) [Fact] public async Task Context_type_not_specified() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseMigrationsEndPoint(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseMigrationsEndPoint(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var formData = new FormUrlEncodedContent(new List>()); @@ -148,12 +174,20 @@ public async Task Context_type_not_specified() [Fact] public async Task Invalid_context_type_specified() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseMigrationsEndPoint(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseMigrationsEndPoint(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var typeName = "You won't find this type ;)"; var formData = new FormUrlEncodedContent(new List> @@ -172,10 +206,18 @@ public async Task Invalid_context_type_specified() [Fact] public async Task Context_not_registered_in_services() { - var builder = new WebHostBuilder() - .Configure(app => app.UseMigrationsEndPoint()) - .ConfigureServices(services => services.AddEntityFrameworkSqlite()); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => app.UseMigrationsEndPoint()) + .ConfigureServices(services => services.AddEntityFrameworkSqlite()); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var formData = new FormUrlEncodedContent(new List> { @@ -197,7 +239,11 @@ public async Task Exception_while_applying_migrations() { using (var database = SqlTestStore.CreateScratch()) { - var builder = new WebHostBuilder() + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() .Configure(app => app.UseMigrationsEndPoint()) .ConfigureServices(services => { @@ -206,7 +252,11 @@ public async Task Exception_while_applying_migrations() optionsBuilder.UseSqlite(database.ConnectionString); }); }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var formData = new FormUrlEncodedContent(new List> { diff --git a/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs b/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs index ef4666ad3143..e24d1bc41a5e 100644 --- a/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs +++ b/src/Middleware/Diagnostics/test/FunctionalTests/TestFixture.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -6,12 +6,14 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.Testing; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.Diagnostics.FunctionalTests { public class TestFixture : IDisposable { private readonly TestServer _server; + private readonly IHost _host; public TestFixture() { @@ -20,10 +22,16 @@ public TestFixture() // (DefaultRequestCulture) is consistent regardless of system configuration or personal preferences. using (new CultureReplacer()) { - var builder = new WebHostBuilder() + _host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() .UseStartup(typeof(TStartup)); + }).Build(); - _server = new TestServer(builder); + _host.Start(); + _server = _host.GetTestServer(); } Client = _server.CreateClient(); @@ -36,6 +44,7 @@ public void Dispose() { Client.Dispose(); _server.Dispose(); + _host.Dispose(); } } } diff --git a/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs b/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs index 26bda1074dc5..c22c9b5368b9 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/DeveloperExceptionPageMiddlewareTest.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Diagnostics @@ -22,17 +23,25 @@ public async Task UnhandledErrorsWriteToDiagnosticWhenUsingExceptionPage() { // Arrange DiagnosticListener diagnosticListener = null; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - diagnosticListener = app.ApplicationServices.GetRequiredService(); - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - throw new Exception("Test exception"); + diagnosticListener = app.ApplicationServices.GetRequiredService(); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var listener = new TestDiagnosticListener(); diagnosticListener.SubscribeWithAdapter(listener); @@ -50,16 +59,24 @@ public async Task UnhandledErrorsWriteToDiagnosticWhenUsingExceptionPage() public async Task ErrorPageWithAcceptHeaderForHtmlReturnsHtml() { // Arrange - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - throw new Exception("Test exception"); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // Act var client = server.CreateClient(); @@ -77,16 +94,24 @@ public async Task ErrorPageWithAcceptHeaderForHtmlReturnsHtml() public async Task ErrorPageWithoutAcceptHeaderForHtmlReturnsPlainText() { // Arrange - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - throw new Exception("Test exception"); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // Act var response = await server.CreateClient().GetAsync("/path"); @@ -102,20 +127,28 @@ public async Task ErrorPageWithoutAcceptHeaderForHtmlReturnsPlainText() public async Task ExceptionPageFiltersAreApplied() { // Arrange - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(); - }) - .Configure(app => - { - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(); + }) + .Configure(app => { - throw new Exception("Test exception"); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // Act var response = await server.CreateClient().GetAsync("/path"); @@ -128,50 +161,68 @@ public async Task ExceptionPageFiltersAreApplied() public async Task ExceptionFilterCallingNextWorks() { // Arrange - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - }) - .Configure(app => - { - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + }) + .Configure(app => { - throw new Exception("Test exception"); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // Act var response = await server.CreateClient().GetAsync("/path"); // Assert Assert.Equal("Bad format exception!", await response.Content.ReadAsStringAsync()); + + await host.StartAsync(); } [Fact] public async Task ExceptionPageFiltersAreAppliedInOrder() { // Arrange - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - throw new Exception("Test exception"); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + }) + .Configure(app => + { + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // Act var response = await server.CreateClient().GetAsync("/path"); @@ -241,17 +292,25 @@ public async Task NullInfoInCompilationException_ShouldNotThrowExceptionGenerati { // Arrange DiagnosticListener diagnosticListener = null; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - diagnosticListener = app.ApplicationServices.GetRequiredService(); - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - throw new CustomCompilationException(failures); + diagnosticListener = app.ApplicationServices.GetRequiredService(); + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new CustomCompilationException(failures); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var listener = new TestDiagnosticListener(); diagnosticListener.SubscribeWithAdapter(listener); diff --git a/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs b/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs index da5c6c60d18a..3c8729a253b8 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/ExceptionHandlerTest.cs @@ -16,6 +16,7 @@ using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Diagnostics @@ -28,28 +29,35 @@ public class ExceptionHandlerTest [InlineData(HttpStatusCode.InternalServerError)] public async Task OnlyHandles_UnhandledExceptions(HttpStatusCode expectedStatusCode) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseExceptionHandler("/handle-errors"); - - app.Map("/handle-errors", (innerAppBuilder) => + webHostBuilder + .UseTestServer() + .Configure(app => { - innerAppBuilder.Run(async (httpContext) => + app.UseExceptionHandler("/handle-errors"); + + app.Map("/handle-errors", (innerAppBuilder) => { - await httpContext.Response.WriteAsync("Handled error in a custom way."); + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync("Handled error in a custom way."); + }); }); + + app.Run((RequestDelegate)(async (context) => + { + context.Response.StatusCode = (int)expectedStatusCode; + context.Response.ContentType = "text/plain; charset=utf-8"; + await context.Response.WriteAsync("An error occurred while adding a product"); + })); }); + }).Build(); - app.Run((RequestDelegate)(async (context) => - { - context.Response.StatusCode = (int)expectedStatusCode; - context.Response.ContentType = "text/plain; charset=utf-8"; - await context.Response.WriteAsync("An error occurred while adding a product"); - })); - }); + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -61,43 +69,50 @@ public async Task OnlyHandles_UnhandledExceptions(HttpStatusCode expectedStatusC [Fact] public async Task DoesNotHandle_UnhandledExceptions_WhenResponseAlreadyStarted() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (httpContext, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - Exception exception = null; - try - { - await next(); - } - catch (InvalidOperationException ex) + app.Use(async (httpContext, next) => { - exception = ex; - } + Exception exception = null; + try + { + await next(); + } + catch (InvalidOperationException ex) + { + exception = ex; + } + + Assert.NotNull(exception); + Assert.Equal("Something bad happened", exception.Message); + }); - Assert.NotNull(exception); - Assert.Equal("Something bad happened", exception.Message); - }); + app.UseExceptionHandler("/handle-errors"); - app.UseExceptionHandler("/handle-errors"); + app.Map("/handle-errors", (innerAppBuilder) => + { + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync("Handled error in a custom way."); + }); + }); - app.Map("/handle-errors", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Run(async (httpContext) => { - await httpContext.Response.WriteAsync("Handled error in a custom way."); + await httpContext.Response.WriteAsync("Hello"); + throw new InvalidOperationException("Something bad happened"); }); }); + }).Build(); - app.Run(async (httpContext) => - { - await httpContext.Response.WriteAsync("Hello"); - throw new InvalidOperationException("Something bad happened"); - }); - }); + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -110,54 +125,61 @@ public async Task DoesNotHandle_UnhandledExceptions_WhenResponseAlreadyStarted() public async Task ClearsResponseBuffer_BeforeRequestIsReexecuted() { var expectedResponseBody = "New response body"; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - // add response buffering - app.Use(async (httpContext, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - var response = httpContext.Response; - var originalResponseBody = response.Body; - var bufferingStream = new MemoryStream(); - response.Body = bufferingStream; - - try + // add response buffering + app.Use(async (httpContext, next) => { - await next(); + var response = httpContext.Response; + var originalResponseBody = response.Body; + var bufferingStream = new MemoryStream(); + response.Body = bufferingStream; + + try + { + await next(); + + response.Body = originalResponseBody; + bufferingStream.Seek(0, SeekOrigin.Begin); + await bufferingStream.CopyToAsync(response.Body); + } + finally + { + response.Body = originalResponseBody; + } + }); - response.Body = originalResponseBody; - bufferingStream.Seek(0, SeekOrigin.Begin); - await bufferingStream.CopyToAsync(response.Body); - } - finally + app.UseExceptionHandler("/handle-errors"); + + app.Map("/handle-errors", (innerAppBuilder) => { - response.Body = originalResponseBody; - } - }); + innerAppBuilder.Run(async (httpContext) => + { + Assert.True(httpContext.Response.Body.CanSeek); + Assert.Equal(0, httpContext.Response.Body.Position); - app.UseExceptionHandler("/handle-errors"); + await httpContext.Response.WriteAsync(expectedResponseBody); + }); + }); - app.Map("/handle-errors", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Run(async (context) => { - Assert.True(httpContext.Response.Body.CanSeek); - Assert.Equal(0, httpContext.Response.Body.Position); + // Write some content into the response before throwing exception + await context.Response.WriteAsync(new string('a', 100)); - await httpContext.Response.WriteAsync(expectedResponseBody); + throw new InvalidOperationException("Invalid input provided."); }); }); + }).Build(); - app.Run(async (context) => - { - // Write some content into the response before throwing exception - await context.Response.WriteAsync(new string('a', 100)); - - throw new InvalidOperationException("Invalid input provided."); - }); - }); + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -181,32 +203,39 @@ public async Task ClearsCacheHeaders_SetByReexecutionPathHandlers() { var expiresTime = DateTime.UtcNow.AddDays(5).ToString("R"); var expectedResponseBody = "Handled error in a custom way."; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseExceptionHandler("/handle-errors"); - - app.Map("/handle-errors", (innerAppBuilder) => + webHostBuilder + .UseTestServer() + .Configure(app => { - innerAppBuilder.Run(async (httpContext) => + app.UseExceptionHandler("/handle-errors"); + + app.Map("/handle-errors", (innerAppBuilder) => { - httpContext.Response.Headers.Add("Cache-Control", new[] { "max-age=600" }); - httpContext.Response.Headers.Add("Pragma", new[] { "max-age=600" }); - httpContext.Response.Headers.Add( - "Expires", new[] { expiresTime }); - httpContext.Response.Headers.Add("ETag", new[] { "12345" }); + innerAppBuilder.Run(async (httpContext) => + { + httpContext.Response.Headers.Add("Cache-Control", new[] { "max-age=600" }); + httpContext.Response.Headers.Add("Pragma", new[] { "max-age=600" }); + httpContext.Response.Headers.Add( + "Expires", new[] { expiresTime }); + httpContext.Response.Headers.Add("ETag", new[] { "12345" }); + + await httpContext.Response.WriteAsync(expectedResponseBody); + }); + }); - await httpContext.Response.WriteAsync(expectedResponseBody); + app.Run((context) => + { + throw new InvalidOperationException("Invalid input provided."); }); }); + }).Build(); - app.Run((context) => - { - throw new InvalidOperationException("Invalid input provided."); - }); - }); + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -230,31 +259,38 @@ public async Task DoesNotModifyCacheHeaders_WhenNoExceptionIsThrown() { var expiresTime = DateTime.UtcNow.AddDays(10).ToString("R"); var expectedResponseBody = "Hello world!"; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseExceptionHandler("/handle-errors"); - - app.Map("/handle-errors", (innerAppBuilder) => + webHostBuilder + .UseTestServer() + .Configure(app => { - innerAppBuilder.Run(async (httpContext) => + app.UseExceptionHandler("/handle-errors"); + + app.Map("/handle-errors", (innerAppBuilder) => { - await httpContext.Response.WriteAsync("Handled error in a custom way."); + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync("Handled error in a custom way."); + }); }); - }); - 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" }); + 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); + await httpContext.Response.WriteAsync(expectedResponseBody); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -280,49 +316,56 @@ public async Task DoesNotModifyCacheHeaders_WhenNoExceptionIsThrown() public async Task DoesNotClearCacheHeaders_WhenResponseHasAlreadyStarted() { var expiresTime = DateTime.UtcNow.AddDays(10).ToString("R"); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (httpContext, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - Exception exception = null; - try - { - await next(); - } - catch (InvalidOperationException ex) + app.Use(async (httpContext, next) => { - exception = ex; - } - - Assert.NotNull(exception); - Assert.Equal("Something bad happened", exception.Message); - }); + Exception exception = null; + try + { + await next(); + } + catch (InvalidOperationException ex) + { + exception = ex; + } + + Assert.NotNull(exception); + Assert.Equal("Something bad happened", exception.Message); + }); - app.UseExceptionHandler("/handle-errors"); + app.UseExceptionHandler("/handle-errors"); - app.Map("/handle-errors", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Map("/handle-errors", (innerAppBuilder) => { - await httpContext.Response.WriteAsync("Handled error in a custom way."); + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync("Handled error in a custom way."); + }); }); - }); - 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" }); + 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("Hello"); + await httpContext.Response.WriteAsync("Hello"); - throw new InvalidOperationException("Something bad happened"); + throw new InvalidOperationException("Something bad happened"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -350,25 +393,33 @@ public async Task HandledErrorsWriteToDiagnosticWhenUsingExceptionHandler() // Arrange DiagnosticListener diagnosticListener = null; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - diagnosticListener = app.ApplicationServices.GetRequiredService(); - - app.UseExceptionHandler("/handle-errors"); - app.Map("/handle-errors", (innerAppBuilder) => + webHostBuilder + .UseTestServer() + .Configure(app => { - innerAppBuilder.Run(async (httpContext) => + diagnosticListener = app.ApplicationServices.GetRequiredService(); + + app.UseExceptionHandler("/handle-errors"); + app.Map("/handle-errors", (innerAppBuilder) => { - await httpContext.Response.WriteAsync("Handled error in a custom way."); + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync("Handled error in a custom way."); + }); + }); + app.Run(context => + { + throw new Exception("Test exception"); }); }); - app.Run(context => - { - throw new Exception("Test exception"); - }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var listener = new TestDiagnosticListener(); diagnosticListener.SubscribeWithAdapter(listener); @@ -395,15 +446,20 @@ public void UsingExceptionHandler_ThrowsAnException_WhenExceptionHandlingPathNot // Arrange DiagnosticListener diagnosticListener = null; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - diagnosticListener = app.ApplicationServices.GetRequiredService(); - app.UseExceptionHandler(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + diagnosticListener = app.ApplicationServices.GetRequiredService(); + app.UseExceptionHandler(); + }); + }).Build(); // Act - var exception = Assert.Throws(() => new TestServer(builder)); + var exception = Assert.Throws(() => host.Start()); // Assert Assert.Equal("An error occurred when configuring the exception handler middleware. " + diff --git a/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs b/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs index c2bb236c4f89..edd2478f4898 100644 --- a/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs +++ b/src/Middleware/Diagnostics/test/UnitTests/StatusCodeMiddlewareTest.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Diagnostics @@ -21,36 +22,44 @@ public async Task Redirect_StatusPage() { var expectedStatusCode = 432; var destination = "/location"; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseStatusCodePagesWithRedirects("/errorPage?id={0}"); - - app.Map(destination, (innerAppBuilder) => + webHostBuilder + .UseTestServer() + .Configure(app => { - innerAppBuilder.Run((httpContext) => + app.UseStatusCodePagesWithRedirects("/errorPage?id={0}"); + + app.Map(destination, (innerAppBuilder) => { - httpContext.Response.StatusCode = expectedStatusCode; - return Task.FromResult(1); + innerAppBuilder.Run((httpContext) => + { + httpContext.Response.StatusCode = expectedStatusCode; + return Task.FromResult(1); + }); }); - }); - app.Map("/errorPage", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Map("/errorPage", (innerAppBuilder) => { - await httpContext.Response.WriteAsync(httpContext.Request.QueryString.Value); + innerAppBuilder.Run(async (httpContext) => + { + await httpContext.Response.WriteAsync(httpContext.Request.QueryString.Value); + }); }); - }); - app.Run((context) => - { - throw new InvalidOperationException($"Invalid input provided. {context.Request.Path}"); + app.Run((context) => + { + throw new InvalidOperationException($"Invalid input provided. {context.Request.Path}"); + }); }); - }); + }).Build(); + + await host.StartAsync(); + var expectedQueryString = $"?id={expectedStatusCode}"; var expectedUri = $"/errorPage{expectedQueryString}"; - using var server = new TestServer(builder); + using var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync(destination); Assert.Equal(HttpStatusCode.Found, response.StatusCode); @@ -67,49 +76,56 @@ public async Task Reexecute_CanRetrieveInformationAboutOriginalRequest() { var expectedStatusCode = 432; var destination = "/location"; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - var beforeNext = context.Request.QueryString; - await next(); - var afterNext = context.Request.QueryString; + app.Use(async (context, next) => + { + var beforeNext = context.Request.QueryString; + await next(); + var afterNext = context.Request.QueryString; - Assert.Equal(beforeNext, afterNext); - }); - app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}"); + Assert.Equal(beforeNext, afterNext); + }); + app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}"); - app.Map(destination, (innerAppBuilder) => - { - innerAppBuilder.Run((httpContext) => + app.Map(destination, (innerAppBuilder) => { - httpContext.Response.StatusCode = expectedStatusCode; - return Task.FromResult(1); + innerAppBuilder.Run((httpContext) => + { + httpContext.Response.StatusCode = expectedStatusCode; + return Task.FromResult(1); + }); }); - }); - app.Map("/errorPage", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Map("/errorPage", (innerAppBuilder) => { - var statusCodeReExecuteFeature = httpContext.Features.Get(); - await httpContext.Response.WriteAsync( - httpContext.Request.QueryString.Value - + ", " - + statusCodeReExecuteFeature.OriginalPath - + ", " - + statusCodeReExecuteFeature.OriginalQueryString); + innerAppBuilder.Run(async (httpContext) => + { + var statusCodeReExecuteFeature = httpContext.Features.Get(); + await httpContext.Response.WriteAsync( + httpContext.Request.QueryString.Value + + ", " + + statusCodeReExecuteFeature.OriginalPath + + ", " + + statusCodeReExecuteFeature.OriginalQueryString); + }); }); - }); - app.Run((context) => - { - throw new InvalidOperationException("Invalid input provided."); + app.Run((context) => + { + throw new InvalidOperationException("Invalid input provided."); + }); }); - }); + }).Build(); - using var server = new TestServer(builder); + await host.StartAsync(); + + using var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync(destination + "?name=James"); var content = await response.Content.ReadAsStringAsync(); @@ -121,50 +137,57 @@ public async Task Reexecute_ClearsEndpointAndRouteData() { var expectedStatusCode = 432; var destination = "/location"; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}"); - - app.Use((context, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Empty(context.Request.RouteValues); - Assert.Null(context.GetEndpoint()); - return next(); - }); + app.UseStatusCodePagesWithReExecute(pathFormat: "/errorPage", queryFormat: "?id={0}"); - app.Map(destination, (innerAppBuilder) => - { - innerAppBuilder.Run((httpContext) => + app.Use((context, next) => { - httpContext.SetEndpoint(new Endpoint((_) => Task.CompletedTask, new EndpointMetadataCollection(), "Test")); - httpContext.Request.RouteValues["John"] = "Doe"; - httpContext.Response.StatusCode = expectedStatusCode; - return Task.CompletedTask; + Assert.Empty(context.Request.RouteValues); + Assert.Null(context.GetEndpoint()); + return next(); }); - }); - app.Map("/errorPage", (innerAppBuilder) => - { - innerAppBuilder.Run(async (httpContext) => + app.Map(destination, (innerAppBuilder) => { - var statusCodeReExecuteFeature = httpContext.Features.Get(); - await httpContext.Response.WriteAsync( - httpContext.Request.QueryString.Value - + ", " - + statusCodeReExecuteFeature.OriginalPath - + ", " - + statusCodeReExecuteFeature.OriginalQueryString); + innerAppBuilder.Run((httpContext) => + { + httpContext.SetEndpoint(new Endpoint((_) => Task.CompletedTask, new EndpointMetadataCollection(), "Test")); + httpContext.Request.RouteValues["John"] = "Doe"; + httpContext.Response.StatusCode = expectedStatusCode; + return Task.CompletedTask; + }); }); - }); - app.Run((context) => - { - throw new InvalidOperationException("Invalid input provided."); + app.Map("/errorPage", (innerAppBuilder) => + { + innerAppBuilder.Run(async (httpContext) => + { + var statusCodeReExecuteFeature = httpContext.Features.Get(); + await httpContext.Response.WriteAsync( + httpContext.Request.QueryString.Value + + ", " + + statusCodeReExecuteFeature.OriginalPath + + ", " + + statusCodeReExecuteFeature.OriginalQueryString); + }); + }); + + app.Run((context) => + { + throw new InvalidOperationException("Invalid input provided."); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using var server = new TestServer(builder); + using var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync(destination + "?name=James"); var content = await response.Content.ReadAsStringAsync(); diff --git a/src/Middleware/Diagnostics/test/testassets/DatabaseErrorPageSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/DatabaseErrorPageSample/Startup.cs index 42bbbdb48301..a59ce7c96acc 100644 --- a/src/Middleware/Diagnostics/test/testassets/DatabaseErrorPageSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/DatabaseErrorPageSample/Startup.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace DatabaseErrorPageSample { @@ -26,15 +27,19 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } diff --git a/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs index 52d67cf9b41e..7ac337c8142e 100644 --- a/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/DeveloperExceptionPageSample/Startup.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Patterns; +using Microsoft.Extensions.Hosting; namespace DeveloperExceptionPageSample { @@ -44,15 +45,19 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Diagnostics/test/testassets/ExceptionHandlerSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/ExceptionHandlerSample/Startup.cs index cf2e57429bc2..b964486fd427 100644 --- a/src/Middleware/Diagnostics/test/testassets/ExceptionHandlerSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/ExceptionHandlerSample/Startup.cs @@ -1,10 +1,12 @@ using System; using System.Text.Encodings.Web; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; +using Microsoft.Extensions.Hosting; namespace ExceptionHandlerSample { @@ -56,15 +58,19 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs index 594cc193405f..e35269915a6a 100644 --- a/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/StatusCodePagesSample/Startup.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; +using Microsoft.Extensions.Hosting; namespace StatusCodePagesSample { @@ -37,7 +38,7 @@ public void Configure(IApplicationBuilder app) { context.Response.StatusCode = int.Parse(requestedStatusCode); - // To turn off the StatusCode feature - For example the below code turns off the StatusCode middleware + // To turn off the StatusCode feature - For example the below code turns off the StatusCode middleware // if the query contains a disableStatusCodePages=true parameter. var disableStatusCodePages = context.Request.Query["disableStatusCodePages"]; if (disableStatusCodePages == "true") @@ -102,15 +103,18 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() - .Build(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Diagnostics/test/testassets/WelcomePageSample/Startup.cs b/src/Middleware/Diagnostics/test/testassets/WelcomePageSample/Startup.cs index 866b10d78816..74ad6f7f5b8d 100644 --- a/src/Middleware/Diagnostics/test/testassets/WelcomePageSample/Startup.cs +++ b/src/Middleware/Diagnostics/test/testassets/WelcomePageSample/Startup.cs @@ -1,5 +1,7 @@ +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; namespace WelcomePageSample { @@ -10,15 +12,18 @@ public void Configure(IApplicationBuilder app) app.UseWelcomePage(); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseIISIntegration() - .UseStartup() - .Build(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs b/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs index 251e324abcfc..4c3dddb7797c 100644 --- a/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs +++ b/src/Middleware/HeaderPropagation/test/HeaderPropagationIntegrationTest.cs @@ -12,6 +12,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.HeaderPropagation.Tests @@ -24,34 +25,41 @@ public async Task HeaderPropagation_WithoutMiddleware_Throws() // Arrange Exception captured = null; - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHttpClient("test").AddHeaderPropagation(); - services.AddHeaderPropagation(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.Headers.Add("X-TraceId"); - }); - }) - .Configure(app => - { - // note: no header propagation middleware - - app.Run(async context => - { - try + services.AddHttpClient("test").AddHeaderPropagation(); + services.AddHeaderPropagation(options => { - var client = context.RequestServices.GetRequiredService().CreateClient("test"); - await client.GetAsync("http://localhost/"); // will throw - } - catch (Exception ex) + options.Headers.Add("X-TraceId"); + }); + }) + .Configure(app => + { + // note: no header propagation middleware + + app.Run(async context => { - captured = ex; - } + try + { + var client = context.RequestServices.GetRequiredService().CreateClient("test"); + await client.GetAsync("http://localhost/"); // will throw + } + catch (Exception ex) + { + captured = ex; + } + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(); @@ -96,10 +104,10 @@ public async Task HeaderInRequest_AddCorrectValue() { // Arrange var handler = new SimpleHandler(); - var builder = CreateBuilder(c => + using var host = await CreateHost(c => c.Headers.Add("in", "out"), handler); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(); @@ -119,13 +127,13 @@ public async Task MultipleHeaders_HeadersInRequest_AddAllHeaders() { // Arrange var handler = new SimpleHandler(); - var builder = CreateBuilder(c => + using var host = await CreateHost(c => { c.Headers.Add("first"); c.Headers.Add("second"); }, handler); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(); @@ -144,15 +152,20 @@ public async Task MultipleHeaders_HeadersInRequest_AddAllHeaders() } [Fact] - public void Builder_UseHeaderPropagation_Without_AddHeaderPropagation_Throws() + public async Task Builder_UseHeaderPropagation_Without_AddHeaderPropagation_Throws() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHeaderPropagation(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHeaderPropagation(); + }); + }).Build(); - var exception = Assert.Throws(() => new TestServer(builder)); + var exception = await Assert.ThrowsAsync(() => host.StartAsync()); Assert.Equal( "Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddHeaderPropagation' inside the call to 'ConfigureServices(...)' in the application startup code.", exception.Message); @@ -163,11 +176,11 @@ public async Task HeaderInRequest_OverrideHeaderPerClient_AddCorrectValue() { // Arrange var handler = new SimpleHandler(); - var builder = CreateBuilder( + using var host = await CreateHost( c => c.Headers.Add("in", "out"), handler, c => c.Headers.Add("out", "different")); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(); @@ -182,32 +195,41 @@ public async Task HeaderInRequest_OverrideHeaderPerClient_AddCorrectValue() Assert.Equal(new[] { "test" }, handler.Headers.GetValues("different")); } - private IWebHostBuilder CreateBuilder(Action configure, HttpMessageHandler primaryHandler, Action configureClient = null) + private async Task CreateHost(Action configure, HttpMessageHandler primaryHandler, Action configureClient = null) { - return new WebHostBuilder() - .Configure(app => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHeaderPropagation(); - app.UseMiddleware(); - }) - .ConfigureServices(services => - { - services.AddHeaderPropagation(configure); - var client = services.AddHttpClient("example.com", c => c.BaseAddress = new Uri("http://example.com")) - .ConfigureHttpMessageHandlerBuilder(b => - { - b.PrimaryHandler = primaryHandler; - }); - - if (configureClient != null) + webHostBuilder + .UseTestServer() + .Configure(app => { - client.AddHeaderPropagation(configureClient); - } - else + app.UseHeaderPropagation(); + app.UseMiddleware(); + }) + .ConfigureServices(services => { - client.AddHeaderPropagation(); - } - }); + services.AddHeaderPropagation(configure); + var client = services.AddHttpClient("example.com", c => c.BaseAddress = new Uri("http://example.com")) + .ConfigureHttpMessageHandlerBuilder(b => + { + b.PrimaryHandler = primaryHandler; + }); + + if (configureClient != null) + { + client.AddHeaderPropagation(configureClient); + } + else + { + client.AddHeaderPropagation(); + } + }); + }).Build(); + + await host.StartAsync(); + + return host; } private class SimpleHandler : DelegatingHandler diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs index 00a7da8d6462..857b5835899f 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckEndpointRouteBuilderExtensionsTest.cs @@ -13,6 +13,7 @@ using Xunit; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.Diagnostics.HealthChecks { @@ -21,21 +22,26 @@ public class HealthCheckEndpointRouteBuilderExtensionsTest [Fact] public void ThrowFriendlyErrorWhenServicesNotRegistered() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRouting(); - app.UseEndpoints(endpoints => + webHostBuilder + .UseTestServer() + .Configure(app => { - endpoints.MapHealthChecks("/healthz"); + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/healthz"); + }); + }) + .ConfigureServices(services => + { + services.AddRouting(); }); - }) - .ConfigureServices(services => - { - services.AddRouting(); - }); + }).Build(); - var ex = Assert.Throws(() => new TestServer(builder)); + var ex = Assert.Throws(() => host.Start()); Assert.Equal( "Unable to find the required services. Please add all the required services by calling " + @@ -48,21 +54,29 @@ public void ThrowFriendlyErrorWhenServicesNotRegistered() public async Task MapHealthChecks_ReturnsOk() { // Arrange - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRouting(); - app.UseEndpoints(endpoints => + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRouting(); + app.UseEndpoints(endpoints => + { + endpoints.MapHealthChecks("/healthz"); + }); + }) + .ConfigureServices(services => { - endpoints.MapHealthChecks("/healthz"); + services.AddRouting(); + services.AddHealthChecks(); }); - }) - .ConfigureServices(services => - { - services.AddRouting(); - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); // Act @@ -78,28 +92,36 @@ public async Task MapHealthChecks_ReturnsOk() public async Task MapHealthChecks_WithOptions_ReturnsOk() { // Arrange - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRouting(); - app.UseEndpoints(endpoints => + webHostBuilder + .UseTestServer() + .Configure(app => { - endpoints.MapHealthChecks("/healthz", new HealthCheckOptions + app.UseRouting(); + app.UseEndpoints(endpoints => { - ResponseWriter = async (context, report) => + endpoints.MapHealthChecks("/healthz", new HealthCheckOptions { - context.Response.ContentType = "text/plain"; - await context.Response.WriteAsync("Custom!"); - } + ResponseWriter = async (context, report) => + { + context.Response.ContentType = "text/plain"; + await context.Response.WriteAsync("Custom!"); + } + }); }); + }) + .ConfigureServices(services => + { + services.AddRouting(); + services.AddHealthChecks(); }); - }) - .ConfigureServices(services => - { - services.AddRouting(); - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); // Act diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs index bffed9ed6631..0d5d648a8734 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareSampleTest.cs @@ -1,10 +1,11 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Diagnostics.HealthChecks @@ -14,10 +15,17 @@ public class HealthCheckMiddlewareSampleTest [Fact] public async Task BasicStartup() { - var builder = new WebHostBuilder() - .UseStartup(); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -29,10 +37,17 @@ public async Task BasicStartup() [Fact] public async Task CustomWriterStartup() { - var builder = new WebHostBuilder() - .UseStartup(); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -45,10 +60,17 @@ public async Task CustomWriterStartup() [Fact] public async Task LivenessProbeStartup_Liveness() { - var builder = new WebHostBuilder() - .UseStartup(); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health/live"); @@ -60,10 +82,17 @@ public async Task LivenessProbeStartup_Liveness() [Fact] public async Task LivenessProbeStartup_Readiness() { - var builder = new WebHostBuilder() - .UseStartup(); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health/ready"); diff --git a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs index 629f46cebe6f..9cbd0532bdac 100644 --- a/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs +++ b/src/Middleware/HealthChecks/test/UnitTests/HealthCheckMiddlewareTests.cs @@ -14,6 +14,7 @@ using System.Net; using System.Threading.Tasks; using Xunit; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.Diagnostics.HealthChecks { @@ -22,13 +23,18 @@ public class HealthCheckMiddlewareTests [Fact] public void ThrowFriendlyErrorWhenServicesNotRegistered() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health"); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }); + }).Build(); - var ex = Assert.Throws(() => new TestServer(builder)); + var ex = Assert.Throws(() => host.Start()); Assert.Equal( "Unable to find the required services. Please add all the required services by calling " + @@ -40,16 +46,24 @@ public void ThrowFriendlyErrorWhenServicesNotRegistered() [Fact] // Matches based on '.Map' public async Task IgnoresRequestThatDoesNotMatchPath() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/frob"); @@ -59,16 +73,24 @@ public async Task IgnoresRequestThatDoesNotMatchPath() [Fact] // Matches based on '.Map' public async Task MatchIsCaseInsensitive() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/HEALTH"); @@ -78,16 +100,24 @@ public async Task MatchIsCaseInsensitive() [Fact] public async Task ReturnsPlainTextStatus() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -100,16 +130,24 @@ public async Task ReturnsPlainTextStatus() [Fact] public async Task StatusCodeIs200IfNoChecks() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -122,19 +160,27 @@ public async Task StatusCodeIs200IfNoChecks() [Fact] public async Task StatusCodeIs200IfAllChecksHealthy() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks() - .AddCheck("Foo", () => HealthCheckResult.Healthy("A-ok!")) - .AddCheck("Bar", () => HealthCheckResult.Healthy("A-ok!")) - .AddCheck("Baz", () => HealthCheckResult.Healthy("A-ok!")); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddCheck("Foo", () => HealthCheckResult.Healthy("A-ok!")) + .AddCheck("Bar", () => HealthCheckResult.Healthy("A-ok!")) + .AddCheck("Baz", () => HealthCheckResult.Healthy("A-ok!")); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -147,19 +193,27 @@ public async Task StatusCodeIs200IfAllChecksHealthy() [Fact] public async Task StatusCodeIs200IfCheckIsDegraded() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks() - .AddCheck("Foo", () => HealthCheckResult.Healthy("A-ok!")) - .AddCheck("Bar", () => HealthCheckResult.Degraded("Not so great.")) - .AddCheck("Baz", () => HealthCheckResult.Healthy("A-ok!")); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddCheck("Foo", () => HealthCheckResult.Healthy("A-ok!")) + .AddCheck("Bar", () => HealthCheckResult.Degraded("Not so great.")) + .AddCheck("Baz", () => HealthCheckResult.Healthy("A-ok!")); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -172,19 +226,27 @@ public async Task StatusCodeIs200IfCheckIsDegraded() [Fact] public async Task StatusCodeIs503IfCheckIsUnhealthy() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks() - .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) - .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) - .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) + .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) + .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -197,19 +259,27 @@ public async Task StatusCodeIs503IfCheckIsUnhealthy() [Fact] public async Task StatusCodeIs503IfCheckHasUnhandledException() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks() - .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) - .AddAsyncCheck("Bar", () => throw null) - .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) + .AddAsyncCheck("Bar", () => throw null) + .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -227,27 +297,35 @@ public async Task CanUseCustomWriter() status = "Unhealthy", }); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - ResponseWriter = (c, r) => + app.UseHealthChecks("/health", new HealthCheckOptions() { - var json = JsonConvert.SerializeObject(new { status = r.Status.ToString(), }); - c.Response.ContentType = "application/json"; - return c.Response.WriteAsync(json); - }, + ResponseWriter = (c, r) => + { + var json = JsonConvert.SerializeObject(new { status = r.Status.ToString(), }); + c.Response.ContentType = "application/json"; + return c.Response.WriteAsync(json); + }, + }); + }) + .ConfigureServices(services => + { + services.AddHealthChecks() + .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) + .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) + .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks() - .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) - .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) - .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -261,22 +339,30 @@ public async Task CanUseCustomWriter() [Fact] public async Task NoResponseWriterReturnsEmptyBody() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health", new HealthCheckOptions() + { + ResponseWriter = null, + }); + }) + .ConfigureServices(services => { - ResponseWriter = null, + services.AddHealthChecks() + .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) + .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) + .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks() - .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) - .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("Pretty bad."))) - .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -288,22 +374,30 @@ public async Task NoResponseWriterReturnsEmptyBody() [Fact] public async Task CanSetCustomStatusCodes() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - ResultStatusCodes = + app.UseHealthChecks("/health", new HealthCheckOptions() { - [HealthStatus.Healthy] = 201, - } + ResultStatusCodes = + { + [HealthStatus.Healthy] = 201, + } + }); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -315,16 +409,24 @@ public async Task CanSetCustomStatusCodes() [Fact] public async Task SetsCacheHeaders() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -339,19 +441,27 @@ public async Task SetsCacheHeaders() [Fact] public async Task CanSuppressCacheHeaders() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - AllowCachingResponses = true, + app.UseHealthChecks("/health", new HealthCheckOptions() + { + AllowCachingResponses = true, + }); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -366,23 +476,31 @@ public async Task CanSuppressCacheHeaders() [Fact] public async Task CanFilterChecks() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health", new HealthCheckOptions() + { + Predicate = (check) => check.Name == "Foo" || check.Name == "Baz", + }); + }) + .ConfigureServices(services => { - Predicate = (check) => check.Name == "Foo" || check.Name == "Baz", + services.AddHealthChecks() + .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) + // Will get filtered out + .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("A-ok!"))) + .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks() - .AddAsyncCheck("Foo", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))) - // Will get filtered out - .AddAsyncCheck("Bar", () => Task.FromResult(HealthCheckResult.Unhealthy("A-ok!"))) - .AddAsyncCheck("Baz", () => Task.FromResult(HealthCheckResult.Healthy("A-ok!"))); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("/health"); @@ -395,17 +513,24 @@ public async Task CanFilterChecks() [Fact] public async Task CanListenWithoutPath_AcceptsRequest() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks(default); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks(default); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health"); @@ -418,17 +543,24 @@ public async Task CanListenWithoutPath_AcceptsRequest() [Fact] public async Task CanListenWithPath_AcceptsRequestWithExtraSlash() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health/"); @@ -439,17 +571,24 @@ public async Task CanListenWithPath_AcceptsRequestWithExtraSlash() [Fact] public async Task CanListenWithPath_AcceptsRequestWithCaseInsensitiveMatch() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/HEALTH"); @@ -462,17 +601,24 @@ public async Task CanListenWithPath_AcceptsRequestWithCaseInsensitiveMatch() [Fact] public async Task CanListenWithPath_RejectsRequestWithExtraSegments() { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseHealthChecks("/health"); - }) - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHealthChecks(); - }); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health"); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); + }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health/detailed"); @@ -484,23 +630,30 @@ public async Task CanListenWithPath_RejectsRequestWithExtraSegments() [Fact] public async Task CanListenWithPath_MultipleMiddleware_LeastSpecificFirst() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - // Throws if used - app.UseHealthChecks("/health", new HealthCheckOptions() + webHostBuilder + .UseTestServer() + .Configure(app => + { + // Throws if used + app.UseHealthChecks("/health", new HealthCheckOptions() + { + ResponseWriter = (c, r) => throw null, + }); + + app.UseHealthChecks("/health/detailed"); + }) + .ConfigureServices(services => { - ResponseWriter = (c, r) => throw null, + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks("/health/detailed"); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health/detailed"); @@ -514,23 +667,30 @@ public async Task CanListenWithPath_MultipleMiddleware_LeastSpecificFirst() [Fact] public async Task CanListenWithPath_MultipleMiddleware_MostSpecificFirst() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHealthChecks("/health/detailed"); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHealthChecks("/health/detailed"); - // Throws if used - app.UseHealthChecks("/health", new HealthCheckOptions() + // Throws if used + app.UseHealthChecks("/health", new HealthCheckOptions() + { + ResponseWriter = (c, r) => throw null, + }); + }) + .ConfigureServices(services => { - ResponseWriter = (c, r) => throw null, + services.AddHealthChecks(); }); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health/detailed"); @@ -543,25 +703,32 @@ public async Task CanListenWithPath_MultipleMiddleware_MostSpecificFirst() [Fact] public async Task CanListenOnPort_AcceptsRequest_OnSpecifiedPort() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(next => async (context) => + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.Use(next => async (context) => + { + // Need to fake setting the connection info. TestServer doesn't + // do that, because it doesn't have a connection. + context.Connection.LocalPort = context.Request.Host.Port.Value; + await next(context); + }); + + app.UseHealthChecks("/health", port: 5001); + }) + .ConfigureServices(services => { - // Need to fake setting the connection info. TestServer doesn't - // do that, because it doesn't have a connection. - context.Connection.LocalPort = context.Request.Host.Port.Value; - await next(context); + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks("/health", port: 5001); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health"); @@ -574,25 +741,32 @@ public async Task CanListenOnPort_AcceptsRequest_OnSpecifiedPort() [Fact] public async Task CanListenOnPortWithoutPath_AcceptsRequest_OnSpecifiedPort() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(next => async (context) => + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.Use(next => async (context) => + { + // Need to fake setting the connection info. TestServer doesn't + // do that, because it doesn't have a connection. + context.Connection.LocalPort = context.Request.Host.Port.Value; + await next(context); + }); + + app.UseHealthChecks(default, port: 5001); + }) + .ConfigureServices(services => { - // Need to fake setting the connection info. TestServer doesn't - // do that, because it doesn't have a connection. - context.Connection.LocalPort = context.Request.Host.Port.Value; - await next(context); + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks(default, port: 5001); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health"); @@ -605,25 +779,32 @@ public async Task CanListenOnPortWithoutPath_AcceptsRequest_OnSpecifiedPort() [Fact] public async Task CanListenOnPort_RejectsRequest_OnOtherPort() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(next => async (context) => + webHostBuilder + .UseTestServer() + .Configure(app => { - // Need to fake setting the connection info. TestServer doesn't - // do that, because it doesn't have a connection. - context.Connection.LocalPort = context.Request.Host.Port.Value; - await next(context); + app.Use(next => async (context) => + { + // Need to fake setting the connection info. TestServer doesn't + // do that, because it doesn't have a connection. + context.Connection.LocalPort = context.Request.Host.Port.Value; + await next(context); + }); + + app.UseHealthChecks("/health", port: 5001); + }) + .ConfigureServices(services => + { + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks("/health", port: 5001); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5000/health"); @@ -634,31 +815,38 @@ public async Task CanListenOnPort_RejectsRequest_OnOtherPort() [Fact] public async Task CanListenOnPort_MultipleMiddleware() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(next => async (context) => + webHostBuilder + .UseTestServer() + .Configure(app => { - // Need to fake setting the connection info. TestServer doesn't - // do that, because it doesn't have a connection. - context.Connection.LocalPort = context.Request.Host.Port.Value; - await next(context); - }); + app.Use(next => async (context) => + { + // Need to fake setting the connection info. TestServer doesn't + // do that, because it doesn't have a connection. + context.Connection.LocalPort = context.Request.Host.Port.Value; + await next(context); + }); + + // Throws if used + app.UseHealthChecks("/health", port: 5001, new HealthCheckOptions() + { + ResponseWriter = (c, r) => throw null, + }); - // Throws if used - app.UseHealthChecks("/health", port: 5001, new HealthCheckOptions() + app.UseHealthChecks("/health/detailed", port: 5001); + }) + .ConfigureServices(services => { - ResponseWriter = (c, r) => throw null, + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks("/health/detailed", port: 5001); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health/detailed"); @@ -671,31 +859,38 @@ public async Task CanListenOnPort_MultipleMiddleware() [Fact] public async Task CanListenOnPort_MultipleMiddleware_DifferentPorts() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(next => async (context) => + webHostBuilder + .UseTestServer() + .Configure(app => { - // Need to fake setting the connection info. TestServer doesn't - // do that, because it doesn't have a connection. - context.Connection.LocalPort = context.Request.Host.Port.Value; - await next(context); - }); + app.Use(next => async (context) => + { + // Need to fake setting the connection info. TestServer doesn't + // do that, because it doesn't have a connection. + context.Connection.LocalPort = context.Request.Host.Port.Value; + await next(context); + }); + + // Throws if used + app.UseHealthChecks("/health", port: 5002, new HealthCheckOptions() + { + ResponseWriter = (c, r) => throw null, + }); - // Throws if used - app.UseHealthChecks("/health", port: 5002, new HealthCheckOptions() + app.UseHealthChecks("/health", port: 5001); + }) + .ConfigureServices(services => { - ResponseWriter = (c, r) => throw null, + services.AddHealthChecks(); }); + }).Build(); - app.UseHealthChecks("/health", port: 5001); - }) - .ConfigureServices(services => - { - services.AddHealthChecks(); - }); + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var response = await client.GetAsync("http://localhost:5001/health"); @@ -704,7 +899,7 @@ public async Task CanListenOnPort_MultipleMiddleware_DifferentPorts() Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); Assert.Equal("Healthy", await response.Content.ReadAsStringAsync()); } - + [Fact] public void HealthCheckOptions_HasDefaultMappingWithDefaultResultStatusCodes() { @@ -714,7 +909,7 @@ public void HealthCheckOptions_HasDefaultMappingWithDefaultResultStatusCodes() Assert.Equal(StatusCodes.Status200OK, options.ResultStatusCodes[HealthStatus.Degraded]); Assert.Equal(StatusCodes.Status503ServiceUnavailable, options.ResultStatusCodes[HealthStatus.Unhealthy]); } - + [Fact] public void HealthCheckOptions_HasDefaultMappingWhenResettingResultStatusCodes() { @@ -724,8 +919,8 @@ public void HealthCheckOptions_HasDefaultMappingWhenResettingResultStatusCodes() Assert.Equal(StatusCodes.Status200OK, options.ResultStatusCodes[HealthStatus.Degraded]); Assert.Equal(StatusCodes.Status503ServiceUnavailable, options.ResultStatusCodes[HealthStatus.Unhealthy]); } - - + + [Fact] public void HealthCheckOptions_DoesNotThrowWhenProperlyConfiguringResultStatusCodes() { @@ -743,18 +938,18 @@ public void HealthCheckOptions_DoesNotThrowWhenProperlyConfiguringResultStatusCo [Fact] public void HealthCheckOptions_ThrowsWhenAHealthStatusIsMissing() { - var exception = Assert.Throws(() => + var exception = Assert.Throws(() => new HealthCheckOptions { ResultStatusCodes = new Dictionary() } ); Assert.Contains($"{nameof(HealthStatus)}.{nameof(HealthStatus.Healthy)}", exception.Message); Assert.Contains($"{nameof(HealthStatus)}.{nameof(HealthStatus.Degraded)}", exception.Message); Assert.Contains($"{nameof(HealthStatus)}.{nameof(HealthStatus.Unhealthy)}", exception.Message); } - + [Fact] public void HealthCheckOptions_ThrowsWhenAHealthStatusIsMissing_MessageDoesNotContainDefinedStatus() { - var exception = Assert.Throws(() => + var exception = Assert.Throws(() => new HealthCheckOptions { ResultStatusCodes = new Dictionary diff --git a/src/Middleware/HealthChecks/test/testassets/HealthChecksSample/Program.cs b/src/Middleware/HealthChecks/test/testassets/HealthChecksSample/Program.cs index 56e6e6478fa4..754ea5260de7 100644 --- a/src/Middleware/HealthChecks/test/testassets/HealthChecksSample/Program.cs +++ b/src/Middleware/HealthChecks/test/testassets/HealthChecksSample/Program.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.IO; +using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace HealthChecksSample @@ -25,12 +27,12 @@ static Program() }; } - public static void Main(string[] args) + public static Task Main(string[] args) { - BuildWebHost(args).Run(); + return BuildWebHost(args).RunAsync(); } - public static IWebHost BuildWebHost(string[] args) + public static IHost BuildWebHost(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) @@ -45,16 +47,20 @@ public static IWebHost BuildWebHost(string[] args) startupType = typeof(BasicStartup); } - return new WebHostBuilder() - .UseConfiguration(config) - .ConfigureLogging(builder => + return new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - builder.SetMinimumLevel(LogLevel.Trace); - builder.AddConfiguration(config); - builder.AddConsole(); + webHostBuilder + .UseConfiguration(config) + .ConfigureLogging(builder => + { + builder.SetMinimumLevel(LogLevel.Trace); + builder.AddConfiguration(config); + builder.AddConsole(); + }) + .UseKestrel() + .UseStartup(startupType); }) - .UseKestrel() - .UseStartup(startupType) .Build(); } diff --git a/src/Middleware/HostFiltering/sample/Program.cs b/src/Middleware/HostFiltering/sample/Program.cs index 0ccc7cdb2e51..8aad652893bf 100644 --- a/src/Middleware/HostFiltering/sample/Program.cs +++ b/src/Middleware/HostFiltering/sample/Program.cs @@ -1,35 +1,41 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace HostFilteringSample { public class Program { - public static void Main(string[] args) + public static Task Main(string[] args) { - BuildWebHost(args).Run(); + return BuildWebHost(args).RunAsync(); } - public static IWebHost BuildWebHost(string[] args) + public static IHost BuildWebHost(string[] args) { - var hostBuilder = new WebHostBuilder() - .ConfigureLogging((_, factory) => + var hostBuilder = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.SetMinimumLevel(LogLevel.Debug); - factory.AddConsole(); - }) - .ConfigureAppConfiguration((hostingContext, config) => - { - var env = hostingContext.HostingEnvironment; - config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) - .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); - }) - .UseKestrel() - .UseStartup(); + webHostBuilder + .ConfigureLogging((_, factory) => + { + factory.SetMinimumLevel(LogLevel.Debug); + factory.AddConsole(); + }) + .ConfigureAppConfiguration((hostingContext, config) => + { + var env = hostingContext.HostingEnvironment; + config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) + .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); + }) + .UseKestrel() + .UseStartup(); + }); return hostBuilder.Build(); } diff --git a/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs b/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs index 921202dbd361..9908f9248cc9 100644 --- a/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs +++ b/src/Middleware/HostFiltering/test/HostFilteringMiddlewareTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; @@ -21,12 +22,20 @@ public class HostFilteringMiddlewareTests [Fact] public async Task MissingConfigThrows() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHostFiltering(); - }); - await Assert.ThrowsAsync(() => new TestServer(builder).SendAsync(_ => { })); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseHostFiltering(); + }); + }).Build(); + + await host.StartAsync(); + + await Assert.ThrowsAsync(() => host.GetTestServer().SendAsync(_ => { })); } [Theory] @@ -34,30 +43,38 @@ public async Task MissingConfigThrows() [InlineData(false, 400)] public async Task AllowsMissingHost(bool allowed, int status) { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddHostFiltering(options => - { - options.AllowEmptyHosts = allowed; - options.AllowedHosts.Add("Localhost"); - }); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use((ctx, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - ctx.Request.Headers.Remove(HeaderNames.Host); - return next(); - }); - app.UseHostFiltering(); - app.Run(c => + services.AddHostFiltering(options => + { + options.AllowEmptyHosts = allowed; + options.AllowedHosts.Add("Localhost"); + }); + }) + .Configure(app => { - Assert.False(c.Request.Headers.TryGetValue(HeaderNames.Host, out var host)); - return Task.CompletedTask; + app.Use((ctx, next) => + { + ctx.Request.Headers.Remove(HeaderNames.Host); + return next(); + }); + app.UseHostFiltering(); + app.Run(c => + { + Assert.False(c.Request.Headers.TryGetValue(HeaderNames.Host, out var host)); + return Task.CompletedTask; + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(status, (int)response.StatusCode); } @@ -67,32 +84,40 @@ public async Task AllowsMissingHost(bool allowed, int status) [InlineData(false, 400)] public async Task AllowsEmptyHost(bool allowed, int status) { - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHostFiltering(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.AllowEmptyHosts = allowed; - options.AllowedHosts.Add("Localhost"); - }); - }) - .Configure(app => - { - app.Use((ctx, next) => - { - ctx.Request.Headers[HeaderNames.Host] = ""; - return next(); - }); - app.UseHostFiltering(); - app.Run(c => + services.AddHostFiltering(options => + { + options.AllowEmptyHosts = allowed; + options.AllowedHosts.Add("Localhost"); + }); + }) + .Configure(app => { - Assert.True(c.Request.Headers.TryGetValue(HeaderNames.Host, out var host)); - Assert.True(StringValues.Equals("", host)); - return Task.CompletedTask; + app.Use((ctx, next) => + { + ctx.Request.Headers[HeaderNames.Host] = ""; + return next(); + }); + app.UseHostFiltering(); + app.Run(c => + { + Assert.True(c.Request.Headers.TryGetValue(HeaderNames.Host, out var host)); + Assert.True(StringValues.Equals("", host)); + return Task.CompletedTask; + }); + app.Run(c => Task.CompletedTask); }); - app.Run(c => Task.CompletedTask); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(status, (int)response.StatusCode); } @@ -113,29 +138,37 @@ public async Task AllowsEmptyHost(bool allowed, int status) [InlineData("xn--c1yn36f:443", "點看")] [InlineData("[::ABC]", "[::aBc]")] [InlineData("[::1]:80", "[::1]")] - public async Task AllowsSpecifiedHost(string host, string allowedHost) + public async Task AllowsSpecifiedHost(string hosturl, string allowedHost) { - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHostFiltering(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - }); - }) - .Configure(app => - { - app.Use((ctx, next) => + services.AddHostFiltering(options => + { + options.AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + }); + }) + .Configure(app => { - // TestHost's ClientHandler doesn't let you set the host header, only the host in the URI - // and that would over-normalize some of our test conditions like casing. - ctx.Request.Headers[HeaderNames.Host] = host; - return next(); + app.Use((ctx, next) => + { + // TestHost's ClientHandler doesn't let you set the host header, only the host in the URI + // and that would over-normalize some of our test conditions like casing. + ctx.Request.Headers[HeaderNames.Host] = hosturl; + return next(); + }); + app.UseHostFiltering(); + app.Run(c => Task.CompletedTask); }); - app.UseHostFiltering(); - app.Run(c => Task.CompletedTask); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateRequest("/").GetAsync(); Assert.Equal(200, (int)response.StatusCode); } @@ -157,29 +190,37 @@ public async Task AllowsSpecifiedHost(string host, string allowedHost) [InlineData("點看", "點看")] [InlineData("[::1", "[::1]")] [InlineData("[::1:80", "[::1]")] - public async Task RejectsMismatchedHosts(string host, string allowedHost) + public async Task RejectsMismatchedHosts(string hosturl, string allowedHost) { - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHostFiltering(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); - }); - }) - .Configure(app => - { - app.Use((ctx, next) => + services.AddHostFiltering(options => + { + options.AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + }); + }) + .Configure(app => { - // TestHost's ClientHandler doesn't let you set the host header, only the host in the URI - // and that would reject some of our test conditions. - ctx.Request.Headers[HeaderNames.Host] = host; - return next(); + app.Use((ctx, next) => + { + // TestHost's ClientHandler doesn't let you set the host header, only the host in the URI + // and that would reject some of our test conditions. + ctx.Request.Headers[HeaderNames.Host] = hosturl; + return next(); + }); + app.UseHostFiltering(); + app.Run(c => throw new NotImplementedException("App")); }); - app.UseHostFiltering(); - app.Run(c => throw new NotImplementedException("App")); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateRequest("/").GetAsync(); Assert.Equal(400, (int)response.StatusCode); } @@ -191,26 +232,34 @@ public async Task SupportsDynamicOptionsReload() config["AllowedHosts"] = "localhost"; var currentHost = "otherHost"; - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddHostFiltering(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.AllowedHosts = new[] { config["AllowedHosts"] }; - }); - services.AddSingleton>(new ConfigurationChangeTokenSource(config)); - }) - .Configure(app => - { - app.Use((ctx, next) => + services.AddHostFiltering(options => + { + options.AllowedHosts = new[] { config["AllowedHosts"] }; + }); + services.AddSingleton>(new ConfigurationChangeTokenSource(config)); + }) + .Configure(app => { - ctx.Request.Headers[HeaderNames.Host] = currentHost; - return next(); + app.Use((ctx, next) => + { + ctx.Request.Headers[HeaderNames.Host] = currentHost; + return next(); + }); + app.UseHostFiltering(); + app.Run(c => Task.CompletedTask); }); - app.UseHostFiltering(); - app.Run(c => Task.CompletedTask); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateRequest("/").GetAsync(); Assert.Equal(400, (int)response.StatusCode); diff --git a/src/Middleware/HttpOverrides/sample/Startup.cs b/src/Middleware/HttpOverrides/sample/Startup.cs index f90cedc70218..69423d52e1c4 100644 --- a/src/Middleware/HttpOverrides/sample/Startup.cs +++ b/src/Middleware/HttpOverrides/sample/Startup.cs @@ -1,7 +1,9 @@ +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.Extensions.Hosting; namespace HttpOverridesSample { @@ -30,15 +32,19 @@ public void Configure(IApplicationBuilder app) } // Entry point for the application. - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - // .UseIIS() // This repo can no longer reference IIS because IISIntegration depends on it. - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + // .UseIIS() // This repo can no longer reference IIS because IISIntegration depends on it. + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs b/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs index 42464ccb9895..6579a17b15ca 100644 --- a/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs +++ b/src/Middleware/HttpOverrides/test/CertificateForwardingTest.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; using Xunit; @@ -42,26 +43,34 @@ public void VerifySettingEmptyHeaderOptionThrows() [Fact] public async Task VerifyHeaderIsUsedIfNoCertificateAlreadySet() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddCertificateForwarding(options => { }); - }) - .Configure(app => - { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - Assert.Null(context.Connection.ClientCertificate); - await next(); - }); - app.UseCertificateForwarding(); - app.Use(async (context, next) => + services.AddCertificateForwarding(options => { }); + }) + .Configure(app => { - Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); - await next(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); + app.UseCertificateForwarding(); + app.Use(async (context, next) => + { + Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); + await next(); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -72,27 +81,35 @@ public async Task VerifyHeaderIsUsedIfNoCertificateAlreadySet() [Fact] public async Task VerifyHeaderOverridesCertificateEvenAlreadySet() { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddCertificateForwarding(options => { }); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - Assert.Null(context.Connection.ClientCertificate); - context.Connection.ClientCertificate = Certificates.SelfSignedNotYetValid; - await next(); - }); - app.UseCertificateForwarding(); - app.Use(async (context, next) => + services.AddCertificateForwarding(options => { }); + }) + .Configure(app => { - Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); - await next(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + context.Connection.ClientCertificate = Certificates.SelfSignedNotYetValid; + await next(); + }); + app.UseCertificateForwarding(); + app.Use(async (context, next) => + { + Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); + await next(); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -103,26 +120,34 @@ public async Task VerifyHeaderOverridesCertificateEvenAlreadySet() [Fact] public async Task VerifySettingTheAzureHeaderOnTheForwarderOptionsWorks() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddCertificateForwarding(options => options.CertificateHeader = "X-ARR-ClientCert"); - }) - .Configure(app => - { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - Assert.Null(context.Connection.ClientCertificate); - await next(); - }); - app.UseCertificateForwarding(); - app.Use(async (context, next) => + services.AddCertificateForwarding(options => options.CertificateHeader = "X-ARR-ClientCert"); + }) + .Configure(app => { - Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); - await next(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); + app.UseCertificateForwarding(); + app.Use(async (context, next) => + { + Assert.Equal(context.Connection.ClientCertificate, Certificates.SelfSignedValidWithNoEku); + await next(); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -133,26 +158,34 @@ public async Task VerifySettingTheAzureHeaderOnTheForwarderOptionsWorks() [Fact] public async Task VerifyACustomHeaderFailsIfTheHeaderIsNotPresent() { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddCertificateForwarding(options => options.CertificateHeader = "some-random-header"); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - Assert.Null(context.Connection.ClientCertificate); - await next(); - }); - app.UseCertificateForwarding(); - app.Use(async (context, next) => + services.AddCertificateForwarding(options => options.CertificateHeader = "some-random-header"); + }) + .Configure(app => { - Assert.Null(context.Connection.ClientCertificate); - await next(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); + app.UseCertificateForwarding(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -163,26 +196,34 @@ public async Task VerifyACustomHeaderFailsIfTheHeaderIsNotPresent() [Fact] public async Task VerifyArrHeaderEncodedCertFailsOnBadEncoding() { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddCertificateForwarding(options => { }); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - Assert.Null(context.Connection.ClientCertificate); - await next(); - }); - app.UseCertificateForwarding(); - app.Use(async (context, next) => + services.AddCertificateForwarding(options => { }); + }) + .Configure(app => { - Assert.Null(context.Connection.ClientCertificate); - await next(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); + app.UseCertificateForwarding(); + app.Use(async (context, next) => + { + Assert.Null(context.Connection.ClientCertificate); + await next(); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { diff --git a/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs b/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs index f427c5b5b404..86d56585218f 100644 --- a/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs +++ b/src/Middleware/HttpOverrides/test/ForwardedHeadersMiddlewareTest.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Net.Http.Headers; using Xunit; @@ -19,15 +20,23 @@ public class ForwardedHeadersMiddlewareTests [Fact] public async Task XForwardedForDefaultSettingsChangeRemoteIpAndPort() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -46,16 +55,24 @@ public async Task XForwardedForDefaultSettingsChangeRemoteIpAndPort() [InlineData(1, "11.111.111.11.12345", "10.0.0.1", 99)] // Invalid public async Task XForwardedForFirstValueIsInvalid(int limit, string header, string expectedIp, int expectedPort) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor, - ForwardLimit = limit, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor, + ForwardLimit = limit, + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -92,20 +109,28 @@ public async Task XForwardedForFirstValueIsInvalid(int limit, string header, str [InlineData(3, "13.113.113.13:34567, 12.112.112.12:23456, 11.111.111.11:12345", "13.113.113.13", 34567, "", true)] public async Task XForwardedForForwardLimit(int limit, string header, string expectedIp, int expectedPort, string remainingHeader, bool requireSymmetry) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor, - RequireHeaderSymmetry = requireSymmetry, - ForwardLimit = limit, - }; - options.KnownProxies.Clear(); - options.KnownNetworks.Clear(); - app.UseForwardedHeaders(options); - }); - var server = new TestServer(builder); + var options = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor, + RequireHeaderSymmetry = requireSymmetry, + ForwardLimit = limit, + }; + options.KnownProxies.Clear(); + options.KnownNetworks.Clear(); + app.UseForwardedHeaders(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -127,15 +152,23 @@ public async Task XForwardedForForwardLimit(int limit, string header, string exp [InlineData("::", false)] public async Task XForwardedForLoopback(string originalIp, bool expectForwarded) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor, + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -185,22 +218,30 @@ public async Task XForwardedForLoopback(string originalIp, bool expectForwarded) [InlineData(3, "13.113.113.13;34567, 12.112.112.12:23456, 11.111.111.11:12345", "10.0.0.1,11.111.111.11,12.112.112.12", "12.112.112.12", 23456, true)] // Invalid 3rd IP public async Task XForwardedForForwardKnownIps(int limit, string header, string knownIPs, string expectedIp, int expectedPort, bool requireSymmetry) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedFor, - RequireHeaderSymmetry = requireSymmetry, - ForwardLimit = limit, - }; - foreach (var ip in knownIPs.Split(',').Select(text => IPAddress.Parse(text))) + webHostBuilder + .UseTestServer() + .Configure(app => { - options.KnownProxies.Add(ip); - } - app.UseForwardedHeaders(options); - }); - var server = new TestServer(builder); + var options = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor, + RequireHeaderSymmetry = requireSymmetry, + ForwardLimit = limit, + }; + foreach (var ip in knownIPs.Split(',').Select(text => IPAddress.Parse(text))) + { + options.KnownProxies.Add(ip); + } + app.UseForwardedHeaders(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -216,15 +257,23 @@ public async Task XForwardedForForwardKnownIps(int limit, string header, string [Fact] public async Task XForwardedForOverrideBadIpDoesntChangeRemoteIp() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -237,15 +286,23 @@ public async Task XForwardedForOverrideBadIpDoesntChangeRemoteIp() [Fact] public async Task XForwardedHostOverrideChangesRequestHost() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedHost + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -291,29 +348,37 @@ public static TheoryData HostHeaderData [Theory] [MemberData(nameof(HostHeaderData))] - public async Task XForwardedHostAllowsValidCharacters(string host) + public async Task XForwardedHostAllowsValidCharacters(string hostHeader) { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedHost - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Equal(host, context.Request.Host.ToString()); - assertsExecuted = true; - return Task.FromResult(0); + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost + }); + app.Run(context => + { + Assert.Equal(hostHeader, context.Request.Host.ToString()); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); await server.SendAsync(c => { - c.Request.Headers["X-Forwarded-Host"] = host; + c.Request.Headers["X-Forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); } @@ -368,29 +433,37 @@ public static TheoryData HostHeaderInvalidData [Theory] [MemberData(nameof(HostHeaderInvalidData))] - public async Task XForwardedHostFailsForInvalidCharacters(string host) + public async Task XForwardedHostFailsForInvalidCharacters(string hostHeader) { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedHost - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.NotEqual(host, context.Request.Host.Value); - assertsExecuted = true; - return Task.FromResult(0); + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost + }); + app.Run(context => + { + Assert.NotEqual(hostHeader, context.Request.Host.Value); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); await server.SendAsync(c => { - c.Request.Headers["X-Forwarded-Host"] = host; + c.Request.Headers["X-Forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); } @@ -411,28 +484,36 @@ await server.SendAsync(c => [InlineData("xn--c1yn36f:443", "點看")] [InlineData("[::ABC]", "[::aBc]")] [InlineData("[::1]:80", "[::1]")] - public async Task XForwardedHostAllowsSpecifiedHost(string host, string allowedHost) + public async Task XForwardedHostAllowsSpecifiedHost(string hostHeader, string allowedHost) { bool assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedHost, - AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost, + AllowedHosts = allowedHost.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) + }); + app.Run(context => + { + Assert.Equal(hostHeader, context.Request.Headers[HeaderNames.Host]); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - app.Run(context => - { - Assert.Equal(host, context.Request.Headers[HeaderNames.Host]); - assertsExecuted = true; - return Task.FromResult(0); - }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.SendAsync(ctx => { - ctx.Request.Headers["X-forwarded-Host"] = host; + ctx.Request.Headers["X-forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); } @@ -454,28 +535,36 @@ public async Task XForwardedHostAllowsSpecifiedHost(string host, string allowedH [InlineData("點看", "點看")] [InlineData("[::1", "[::1]")] [InlineData("[::1:80", "[::1]")] - public async Task XForwardedHostFailsMismatchedHosts(string host, string allowedHost) + public async Task XForwardedHostFailsMismatchedHosts(string hostHeader, string allowedHost) { bool assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedHost, - AllowedHosts = new[] { allowedHost } - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.NotEqual(host, context.Request.Headers[HeaderNames.Host]); - assertsExecuted = true; - return Task.FromResult(0); + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost, + AllowedHosts = new[] { allowedHost } + }); + app.Run(context => + { + Assert.NotEqual(hostHeader, context.Request.Headers[HeaderNames.Host]); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.SendAsync(ctx => { - ctx.Request.Headers["X-forwarded-Host"] = host; + ctx.Request.Headers["X-forwarded-Host"] = hostHeader; }); Assert.True(assertsExecuted); } @@ -484,23 +573,31 @@ public async Task XForwardedHostFailsMismatchedHosts(string host, string allowed public async Task XForwardedHostStopsAtFirstUnspecifiedHost() { bool assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedHost, - ForwardLimit = 10, - AllowedHosts = new[] { "bar.com", "*.foo.com" } + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedHost, + ForwardLimit = 10, + AllowedHosts = new[] { "bar.com", "*.foo.com" } + }); + app.Run(context => + { + Assert.Equal("bar.foo.com:432", context.Request.Headers[HeaderNames.Host]); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - app.Run(context => - { - Assert.Equal("bar.foo.com:432", context.Request.Headers[HeaderNames.Host]); - assertsExecuted = true; - return Task.FromResult(0); - }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.SendAsync(ctx => { ctx.Request.Headers["X-forwarded-Host"] = "stuff:523, bar.foo.com:432, bar.com:80"; @@ -518,16 +615,24 @@ public async Task XForwardedHostStopsAtFirstUnspecifiedHost() [InlineData(10, "h3, h2, h1", "h3")] public async Task XForwardedProtoOverrideChangesRequestProtocol(int limit, string header, string expected) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedProto, - ForwardLimit = limit, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto, + ForwardLimit = limit, + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -559,21 +664,29 @@ public async Task XForwardedProtoAcceptsValidProtocols(string scheme) { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions - { - ForwardedHeaders = ForwardedHeaders.XForwardedProto - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Equal(scheme, context.Request.Scheme); - assertsExecuted = true; - return Task.FromResult(0); + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto + }); + app.Run(context => + { + Assert.Equal(scheme, context.Request.Scheme); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); await server.SendAsync(c => { @@ -608,21 +721,29 @@ public async Task XForwardedProtoRejectsInvalidProtocols(string scheme) { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedProto, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto, + }); + app.Run(context => + { + Assert.Equal("http", context.Request.Scheme); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - app.Run(context => - { - Assert.Equal("http", context.Request.Scheme); - assertsExecuted = true; - return Task.FromResult(0); - }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); await server.SendAsync(c => { @@ -642,17 +763,25 @@ await server.SendAsync(c => [InlineData(10, "h3, h2, h1", "::1, badip, ::1", "h1")] public async Task XForwardedProtoOverrideLimitedByXForwardedForCount(int limit, string protoHeader, string forHeader, string expected) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, - RequireHeaderSymmetry = true, - ForwardLimit = limit, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, + RequireHeaderSymmetry = true, + ForwardLimit = limit, + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -676,17 +805,25 @@ public async Task XForwardedProtoOverrideLimitedByXForwardedForCount(int limit, [InlineData(10, "h3, h2, h1", "::1, badip, ::1", "h1")] public async Task XForwardedProtoOverrideCanBeIndependentOfXForwardedForCount(int limit, string protoHeader, string forHeader, string expected) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, - RequireHeaderSymmetry = false, - ForwardLimit = limit, + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, + RequireHeaderSymmetry = false, + ForwardLimit = limit, + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -712,23 +849,31 @@ public async Task XForwardedProtoOverrideCanBeIndependentOfXForwardedForCount(in [InlineData("h2, h1", "E::, D::", "F::", true, "http")] public async Task XForwardedProtoOverrideLimitedByLoopback(string protoHeader, string forHeader, string remoteIp, bool loopback, string expected) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, - RequireHeaderSymmetry = true, - ForwardLimit = 5, - }; - if (!loopback) - { - options.KnownNetworks.Clear(); - options.KnownProxies.Clear(); - } - app.UseForwardedHeaders(options); - }); - var server = new TestServer(builder); + var options = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor, + RequireHeaderSymmetry = true, + ForwardLimit = 5, + }; + if (!loopback) + { + options.KnownNetworks.Clear(); + options.KnownProxies.Clear(); + } + app.UseForwardedHeaders(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -753,15 +898,23 @@ public void AllForwardsDisabledByDefault() [Fact] public async Task AllForwardsEnabledChangeRequestRemoteIpHostandProtocol() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.All + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.All + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -778,15 +931,23 @@ public async Task AllForwardsEnabledChangeRequestRemoteIpHostandProtocol() [Fact] public async Task AllOptionsDisabledRequestDoesntChange() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.None + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.None + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -803,15 +964,23 @@ public async Task AllOptionsDisabledRequestDoesntChange() [Fact] public async Task PartiallyEnabledForwardsPartiallyChangesRequest() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto + app.UseForwardedHeaders(new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -852,12 +1021,20 @@ public async Task XForwardForIPv4ToIPv6Mapping(string forHeader, string knownPro options.KnownNetworks.Add(new IPNetwork(networkIp, prefixLength)); } - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseForwardedHeaders(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseForwardedHeaders(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -872,23 +1049,31 @@ public async Task XForwardForIPv4ToIPv6Mapping(string forHeader, string knownPro [InlineData(2, "httpa, httpb, httpc", "httpb", "httpa")] public async Task ForwardersWithDIOptionsRunsOnce(int limit, string header, string expectedScheme, string remainingHeader) { - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.Configure(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.ForwardedHeaders = ForwardedHeaders.XForwardedProto; - options.KnownProxies.Clear(); - options.KnownNetworks.Clear(); - options.ForwardLimit = limit; + services.Configure(options => + { + options.ForwardedHeaders = ForwardedHeaders.XForwardedProto; + options.KnownProxies.Clear(); + options.KnownNetworks.Clear(); + options.ForwardLimit = limit; + }); + }) + .Configure(app => + { + app.UseForwardedHeaders(); + app.UseForwardedHeaders(); }); - }) - .Configure(app => - { - app.UseForwardedHeaders(); - app.UseForwardedHeaders(); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { @@ -904,20 +1089,28 @@ public async Task ForwardersWithDIOptionsRunsOnce(int limit, string header, stri [InlineData(2, "httpa, httpb, httpc", "httpa", "")] public async Task ForwardersWithDirectOptionsRunsTwice(int limit, string header, string expectedScheme, string remainingHeader) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new ForwardedHeadersOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - ForwardedHeaders = ForwardedHeaders.XForwardedProto, - ForwardLimit = limit, - }; - options.KnownProxies.Clear(); - options.KnownNetworks.Clear(); - app.UseForwardedHeaders(options); - app.UseForwardedHeaders(options); - }); - var server = new TestServer(builder); + var options = new ForwardedHeadersOptions + { + ForwardedHeaders = ForwardedHeaders.XForwardedProto, + ForwardLimit = limit, + }; + options.KnownProxies.Clear(); + options.KnownNetworks.Clear(); + app.UseForwardedHeaders(options); + app.UseForwardedHeaders(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var context = await server.SendAsync(c => { diff --git a/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs b/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs index fcd47da8ba83..d36cc29c77a8 100644 --- a/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs +++ b/src/Middleware/HttpOverrides/test/HttpMethodOverrideMiddlewareTest.cs @@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.HttpOverrides @@ -17,18 +18,26 @@ public class HttpMethodOverrideMiddlewareTest public async Task XHttpMethodOverrideHeaderAvaiableChangesRequestMethod() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - assertsExecuted = true; - Assert.Equal("DELETE", context.Request.Method); - return Task.FromResult(0); + app.UseHttpMethodOverride(); + app.Run(context => + { + assertsExecuted = true; + Assert.Equal("DELETE", context.Request.Method); + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Headers.Add("X-Http-Method-Override", "DELETE"); @@ -40,18 +49,26 @@ public async Task XHttpMethodOverrideHeaderAvaiableChangesRequestMethod() public async Task XHttpMethodOverrideHeaderUnavaiableDoesntChangeRequestMethod() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Equal("POST",context.Request.Method); - assertsExecuted = true; - return Task.FromResult(0); + app.UseHttpMethodOverride(); + app.Run(context => + { + Assert.Equal("POST", context.Request.Method); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); await server.CreateClient().SendAsync(req); @@ -62,18 +79,26 @@ public async Task XHttpMethodOverrideHeaderUnavaiableDoesntChangeRequestMethod() public async Task XHttpMethodOverrideFromGetRequestDoesntChangeMethodType() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Equal("GET", context.Request.Method); - assertsExecuted = true; - return Task.FromResult(0); + app.UseHttpMethodOverride(); + app.Run(context => + { + Assert.Equal("GET", context.Request.Method); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, ""); await server.CreateClient().SendAsync(req); @@ -85,21 +110,29 @@ public async Task XHttpMethodOverrideFromGetRequestDoesntChangeMethodType() public async Task FormFieldAvailableChangesRequestMethod() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(new HttpMethodOverrideOptions() - { - FormFieldName = "_METHOD" - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Equal("DELETE", context.Request.Method); - assertsExecuted = true; - return Task.FromResult(0); + app.UseHttpMethodOverride(new HttpMethodOverrideOptions() + { + FormFieldName = "_METHOD" + }); + app.Run(context => + { + Assert.Equal("DELETE", context.Request.Method); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Content = new FormUrlEncodedContent(new Dictionary() @@ -116,21 +149,29 @@ public async Task FormFieldAvailableChangesRequestMethod() public async Task FormFieldUnavailableDoesNotChangeRequestMethod() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(new HttpMethodOverrideOptions() - { - FormFieldName = "_METHOD" - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Equal("POST", context.Request.Method); - assertsExecuted = true; - return Task.FromResult(0); + app.UseHttpMethodOverride(new HttpMethodOverrideOptions() + { + FormFieldName = "_METHOD" + }); + app.Run(context => + { + Assert.Equal("POST", context.Request.Method); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Content = new FormUrlEncodedContent(new Dictionary() @@ -146,21 +187,29 @@ public async Task FormFieldUnavailableDoesNotChangeRequestMethod() public async Task FormFieldEmptyDoesNotChangeRequestMethod() { var assertsExecuted = false; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpMethodOverride(new HttpMethodOverrideOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - FormFieldName = "_METHOD" + app.UseHttpMethodOverride(new HttpMethodOverrideOptions() + { + FormFieldName = "_METHOD" + }); + app.Run(context => + { + Assert.Equal("POST", context.Request.Method); + assertsExecuted = true; + return Task.FromResult(0); + }); }); - app.Run(context => - { - Assert.Equal("POST", context.Request.Method); - assertsExecuted = true; - return Task.FromResult(0); - }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Post, ""); req.Content = new FormUrlEncodedContent(new Dictionary() diff --git a/src/Middleware/HttpsPolicy/sample/Startup.cs b/src/Middleware/HttpsPolicy/sample/Startup.cs index 6f2f5f7eb51d..cd83e7f3df7d 100644 --- a/src/Middleware/HttpsPolicy/sample/Startup.cs +++ b/src/Middleware/HttpsPolicy/sample/Startup.cs @@ -49,30 +49,34 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment environment) } // Entry point for the application. - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel( - options => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(new IPEndPoint(IPAddress.Loopback, 5001), listenOptions => + webHostBuilder + .UseKestrel( + options => { - listenOptions.UseHttps("testCert.pfx", "testPassword"); - }); - options.Listen(new IPEndPoint(IPAddress.Loopback, 5000), listenOptions => + options.Listen(new IPEndPoint(IPAddress.Loopback, 5001), listenOptions => + { + listenOptions.UseHttps("testCert.pfx", "testPassword"); + }); + options.Listen(new IPEndPoint(IPAddress.Loopback, 5000), listenOptions => + { + }); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) // for the cert file + .ConfigureLogging(factory => { - }); + factory.SetMinimumLevel(LogLevel.Debug); + factory.AddConsole(); + }) + .UseStartup(); }) - .UseContentRoot(Directory.GetCurrentDirectory()) // for the cert file - .ConfigureLogging(factory => - { - factory.SetMinimumLevel(LogLevel.Debug); - factory.AddConsole(); - }) - .UseStartup() .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs b/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs index 0cb5f5755c96..232f2e474803 100644 --- a/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs +++ b/src/Middleware/HttpsPolicy/test/HstsMiddlewareTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -12,6 +12,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Microsoft.Net.Http.Headers; @@ -24,20 +25,27 @@ public class HstsMiddlewareTests [Fact] public async Task SetOptionsWithDefault_SetsMaxAgeToCorrectValue() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - }) - .Configure(app => - { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); client.BaseAddress = new Uri("https://example.com:5050"); @@ -58,25 +66,33 @@ public async Task SetOptionsWithDefault_SetsMaxAgeToCorrectValue() [InlineData(50000, true, true, "max-age=50000; includeSubDomains; preload")] public async Task SetOptionsThroughConfigure_SetsHeaderCorrectly(int maxAge, bool includeSubDomains, bool preload, string expected) { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.Configure(options => { - options.Preload = preload; - options.IncludeSubDomains = includeSubDomains; - options.MaxAge = TimeSpan.FromSeconds(maxAge); - }); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - return context.Response.WriteAsync("Hello world"); + services.Configure(options => + { + options.Preload = preload; + options.IncludeSubDomains = includeSubDomains; + options.MaxAge = TimeSpan.FromSeconds(maxAge); + }); + }) + .Configure(app => + { + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); client.BaseAddress = new Uri("https://example.com:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -96,25 +112,33 @@ public async Task SetOptionsThroughConfigure_SetsHeaderCorrectly(int maxAge, boo [InlineData(50000, true, true, "max-age=50000; includeSubDomains; preload")] public async Task SetOptionsThroughHelper_SetsHeaderCorrectly(int maxAge, bool includeSubDomains, bool preload, string expected) { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddHsts(options => { - options.Preload = preload; - options.IncludeSubDomains = includeSubDomains; - options.MaxAge = TimeSpan.FromSeconds(maxAge); - }); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - return context.Response.WriteAsync("Hello world"); + services.AddHsts(options => + { + options.Preload = preload; + options.IncludeSubDomains = includeSubDomains; + options.MaxAge = TimeSpan.FromSeconds(maxAge); + }); + }) + .Configure(app => + { + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); client.BaseAddress = new Uri("https://example.com:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -131,29 +155,37 @@ public async Task SetOptionsThroughHelper_SetsHeaderCorrectly(int maxAge, bool i [InlineData("LOCALHOST")] [InlineData("127.0.0.1")] [InlineData("[::1]")] - public async Task DefaultExcludesCommonLocalhostDomains_DoesNotSetHstsHeader(string host) + public async Task DefaultExcludesCommonLocalhostDomains_DoesNotSetHstsHeader(string hostUrl) { var sink = new TestSink( TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddSingleton(loggerFactory); - }) - .Configure(app => + + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - return context.Response.WriteAsync("Hello world"); + services.AddSingleton(loggerFactory); + }) + .Configure(app => + { + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); - client.BaseAddress = new Uri($"https://{host}:5050"); + client.BaseAddress = new Uri($"https://{hostUrl}:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); var response = await client.SendAsync(request); @@ -166,41 +198,49 @@ public async Task DefaultExcludesCommonLocalhostDomains_DoesNotSetHstsHeader(str Assert.Single(logMessages); var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); - Assert.Equal($"The host '{host}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true); + Assert.Equal($"The host '{hostUrl}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true); } [Theory] [InlineData("localhost")] [InlineData("127.0.0.1")] [InlineData("[::1]")] - public async Task AllowLocalhostDomainsIfListIsReset_SetHstsHeader(string host) + public async Task AllowLocalhostDomainsIfListIsReset_SetHstsHeader(string hostUrl) { var sink = new TestSink( TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - - services.AddHsts(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.ExcludedHosts.Clear(); - }); - }) - .Configure(app => - { - app.UseHsts(); - app.Run(context => + services.AddSingleton(loggerFactory); + + services.AddHsts(options => + { + options.ExcludedHosts.Clear(); + }); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); - client.BaseAddress = new Uri($"https://{host}:5050"); + client.BaseAddress = new Uri($"https://{hostUrl}:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); var response = await client.SendAsync(request); @@ -215,38 +255,47 @@ public async Task AllowLocalhostDomainsIfListIsReset_SetHstsHeader(string host) Assert.Equal(LogLevel.Trace, message.LogLevel); Assert.Equal("Adding HSTS header to response.", message.State.ToString()); } - + [Theory] [InlineData("example.com")] [InlineData("Example.com")] [InlineData("EXAMPLE.COM")] - public async Task AddExcludedDomains_DoesNotAddHstsHeader(string host) + public async Task AddExcludedDomains_DoesNotAddHstsHeader(string hostUrl) { var sink = new TestSink( TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - - services.AddHsts(options => { - options.ExcludedHosts.Add(host); - }); - }) - .Configure(app => - { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - return context.Response.WriteAsync("Hello world"); + services.AddSingleton(loggerFactory); + + services.AddHsts(options => + { + options.ExcludedHosts.Add(hostUrl); + }); + }) + .Configure(app => + { + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); - client.BaseAddress = new Uri($"https://{host}:5050"); + client.BaseAddress = new Uri($"https://{hostUrl}:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); var response = await client.SendAsync(request); @@ -259,7 +308,7 @@ public async Task AddExcludedDomains_DoesNotAddHstsHeader(string host) Assert.Single(logMessages); var message = logMessages.Single(); Assert.Equal(LogLevel.Debug, message.LogLevel); - Assert.Equal($"The host '{host}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true); + Assert.Equal($"The host '{hostUrl}' is excluded. Skipping HSTS header.", message.State.ToString(), ignoreCase: true); } [Fact] @@ -270,20 +319,28 @@ public async Task WhenRequestIsInsecure_DoesNotAddHstsHeader() TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddSingleton(loggerFactory); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - return context.Response.WriteAsync("Hello world"); + services.AddSingleton(loggerFactory); + }) + .Configure(app => + { + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); client.BaseAddress = new Uri("http://example.com:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -309,20 +366,27 @@ public async Task WhenRequestIsSecure_AddsHstsHeader() TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddSingleton(loggerFactory); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHsts(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - return context.Response.WriteAsync("Hello world"); + services.AddSingleton(loggerFactory); + }) + .Configure(app => + { + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + var server = host.GetTestServer(); var client = server.CreateClient(); client.BaseAddress = new Uri("https://example.com:5050"); var request = new HttpRequestMessage(HttpMethod.Get, ""); diff --git a/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs b/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs index 2b9b3d3b4924..d246c6255f01 100644 --- a/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs +++ b/src/Middleware/HttpsPolicy/test/HttpsPolicyTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -13,6 +13,7 @@ using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Net.Http.Headers; using Xunit; @@ -30,36 +31,41 @@ public class HttpsPolicyTests [InlineData(302, 5050, 2592000, true, true, "max-age=2592000; includeSubDomains; preload", "https://localhost:5050/")] public async Task SetsBothHstsAndHttpsRedirection_RedirectOnFirstRequest_HstsOnSecondRequest(int statusCode, int? tlsPort, int maxAge, bool includeSubDomains, bool preload, string expectedHstsHeader, string expectedUrl) { - - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.Configure(options => - { - options.RedirectStatusCode = statusCode; - options.HttpsPort = tlsPort; - }); - services.Configure(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.IncludeSubDomains = includeSubDomains; - options.MaxAge = TimeSpan.FromSeconds(maxAge); - options.Preload = preload; - options.ExcludedHosts.Clear(); // allowing localhost for testing - }); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.UseHsts(); - app.Run(context => + services.Configure(options => + { + options.RedirectStatusCode = statusCode; + options.HttpsPort = tlsPort; + }); + services.Configure(options => + { + options.IncludeSubDomains = includeSubDomains; + options.MaxAge = TimeSpan.FromSeconds(maxAge); + options.Preload = preload; + options.ExcludedHosts.Clear(); // allowing localhost for testing + }); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.UseHsts(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var featureCollection = new FeatureCollection(); - featureCollection.Set(new ServerAddressesFeature()); - var server = new TestServer(builder, featureCollection); + var server = host.GetTestServer(); + server.Features.Set(new ServerAddressesFeature()); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); diff --git a/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs b/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs index ef0b0c368598..c2a4e8e1caca 100644 --- a/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs +++ b/src/Middleware/HttpsPolicy/test/HttpsRedirectionMiddlewareTests.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -8,11 +8,13 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Xunit; @@ -28,21 +30,28 @@ public async Task SetOptions_NotEnabledByDefault() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -71,26 +80,33 @@ public async Task SetOptions_SetStatusCodeHttpsPort(int statusCode, int? httpsPo TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - services.Configure(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.RedirectStatusCode = statusCode; - options.HttpsPort = httpsPort; - }); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + services.AddSingleton(loggerFactory); + services.Configure(options => + { + options.RedirectStatusCode = statusCode; + options.HttpsPort = httpsPort; + }); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -120,26 +136,33 @@ public async Task SetOptionsThroughHelperMethod_SetStatusCodeAndHttpsPort(int st TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - services.AddHttpsRedirection(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.RedirectStatusCode = statusCode; - options.HttpsPort = httpsPort; - }); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + services.AddSingleton(loggerFactory); + services.AddHttpsRedirection(options => + { + options.RedirectStatusCode = statusCode; + options.HttpsPort = httpsPort; + }); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -169,34 +192,39 @@ public async Task SetOptionsThroughHelperMethod_SetStatusCodeAndHttpsPort(int st public async Task SetHttpsPortEnvironmentVariableAndServerFeature_ReturnsCorrectStatusCodeOnResponse( int? optionsHttpsPort, string configHttpsPort, string serverAddressFeatureUrl, string expectedUrl) { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddHttpsRedirection(options => - { - options.HttpsPort = optionsHttpsPort; - }); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => - { - return context.Response.WriteAsync("Hello world"); - }); - }); - - builder.UseSetting("HTTPS_PORT", configHttpsPort); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddHttpsRedirection(options => + { + options.HttpsPort = optionsHttpsPort; + }); + }) + .Configure(app => + { + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); + }); - var featureCollection = new FeatureCollection(); - featureCollection.Set(new ServerAddressesFeature()); + webHostBuilder.UseSetting("HTTPS_PORT", configHttpsPort); + }).Build(); - var server = new TestServer(builder, featureCollection); + var server = host.GetTestServer(); + server.Features.Set(new ServerAddressesFeature()); if (serverAddressFeatureUrl != null) { server.Features.Get().Addresses.Add(serverAddressFeatureUrl); } + await host.StartAsync(); + var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -213,25 +241,30 @@ public async Task SetServerAddressesFeature_SingleHttpsAddress_Success() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); - var featureCollection = new FeatureCollection(); - featureCollection.Set(new ServerAddressesFeature()); - var server = new TestServer(builder, featureCollection); + var server = host.GetTestServer(); + server.Features.Set(new ServerAddressesFeature()); server.Features.Get().Addresses.Add("https://localhost:5050"); + await host.StartAsync(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -259,27 +292,33 @@ public async Task SetServerAddressesFeature_MultipleHttpsAddresses_LogsAndFailsT TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); - var featureCollection = new FeatureCollection(); - featureCollection.Set(new ServerAddressesFeature()); - var server = new TestServer(builder, featureCollection); + var server = host.GetTestServer(); + server.Features.Set(new ServerAddressesFeature()); server.Features.Get().Addresses.Add("https://localhost:5050"); server.Features.Get().Addresses.Add("https://localhost:5051"); + await host.StartAsync(); + var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -303,27 +342,32 @@ public async Task SetServerAddressesFeature_MultipleHttpsAddressesWithSamePort_S TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); - - var featureCollection = new FeatureCollection(); - featureCollection.Set(new ServerAddressesFeature()); - var server = new TestServer(builder, featureCollection); + }).Build(); + var server = host.GetTestServer(); + server.Features.Set(new ServerAddressesFeature()); server.Features.Get().Addresses.Add("https://localhost:5050"); server.Features.Get().Addresses.Add("https://example.com:5050"); + await host.StartAsync(); + var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -351,21 +395,28 @@ public async Task NoServerAddressFeature_DoesNotThrow_DoesNotRedirect() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddSingleton(loggerFactory); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - return context.Response.WriteAsync("Hello world"); + services.AddSingleton(loggerFactory); + }) + .Configure(app => + { + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); var response = await client.SendAsync(request); @@ -386,23 +437,29 @@ public async Task SetNullAddressFeature_DoesNotThrow() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - }) - .Configure(app => - { - app.UseHttpsRedirection(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddSingleton(loggerFactory); + }) + .Configure(app => { - return context.Response.WriteAsync("Hello world"); + app.UseHttpsRedirection(); + app.Run(context => + { + return context.Response.WriteAsync("Hello world"); + }); }); - }); + }).Build(); + + var server = host.GetTestServer(); + server.Features.Set(null); - var featureCollection = new FeatureCollection(); - featureCollection.Set(null); - var server = new TestServer(builder, featureCollection); + await host.StartAsync(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); diff --git a/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs b/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs index 72e729285927..9aa142ce55a9 100644 --- a/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs +++ b/src/Middleware/Localization.Routing/test/RouteDataRequestCultureProviderTest.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Localization.Routing @@ -30,50 +31,57 @@ public async Task GetCultureInfo_FromRouteData( string expectedCulture, string expectedUICulture) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRouter(routes => + webHostBuilder + .UseTestServer() + .Configure(app => { - routes.MapMiddlewareRoute(routeTemplate, fork => + app.UseRouter(routes => { - var options = new RequestLocalizationOptions + routes.MapMiddlewareRoute(routeTemplate, fork => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }; + options.RequestCultureProviders = new[] { - new CultureInfo("ar-YE") - } - }; - options.RequestCultureProviders = new[] - { - new RouteDataRequestCultureProvider() - { - Options = options - } - }; - fork.UseRequestLocalization(options); + new RouteDataRequestCultureProvider() + { + Options = options + } + }; + fork.UseRequestLocalization(options); - fork.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - return context.Response.WriteAsync( - $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + fork.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + return context.Response.WriteAsync( + $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + }); }); }); + }) + .ConfigureServices(services => + { + services.AddRouting(); }); - }) - .ConfigureServices(services => - { - services.AddRouting(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(requestUrl); @@ -87,32 +95,39 @@ public async Task GetCultureInfo_FromRouteData( [Fact] public async Task GetDefaultCultureInfo_IfCultureKeysAreMissing() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions - { - DefaultRequestCulture = new RequestCulture("en-US") - }; - options.RequestCultureProviders = new[] + webHostBuilder + .UseTestServer() + .Configure(app => { - new RouteDataRequestCultureProvider() + var options = new RequestLocalizationOptions { - Options = options - } - }; - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; + DefaultRequestCulture = new RequestCulture("en-US") + }; + options.RequestCultureProviders = new[] + { + new RouteDataRequestCultureProvider() + { + Options = options + } + }; + app.UseRequestLocalization(options); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; - return context.Response.WriteAsync( - $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + return context.Response.WriteAsync( + $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page"); @@ -135,53 +150,60 @@ public async Task GetCultureInfo_FromRouteData_WithCustomKeys( string expectedCulture, string expectedUICulture) { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRouter(routes => + webHostBuilder + .UseTestServer() + .Configure(app => { - routes.MapMiddlewareRoute(routeTemplate, fork => + app.UseRouter(routes => { - var options = new RequestLocalizationOptions + routes.MapMiddlewareRoute(routeTemplate, fork => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }; + options.RequestCultureProviders = new[] { - new CultureInfo("ar-YE") - } - }; - options.RequestCultureProviders = new[] - { - new RouteDataRequestCultureProvider() + new RouteDataRequestCultureProvider() + { + Options = options, + RouteDataStringKey = "c", + UIRouteDataStringKey = "uic" + } + }; + fork.UseRequestLocalization(options); + + fork.Run(context => { - Options = options, - RouteDataStringKey = "c", - UIRouteDataStringKey = "uic" - } - }; - fork.UseRequestLocalization(options); - - fork.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; - return context.Response.WriteAsync( - $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + return context.Response.WriteAsync( + $"{requestCulture.Culture.Name},{requestCulture.UICulture.Name}"); + }); }); }); + }) + .ConfigureServices(services => + { + services.AddRouting(); }); - }) - .ConfigureServices(services => - { - services.AddRouting(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(requestUrl); diff --git a/src/Middleware/Localization/sample/Startup.cs b/src/Middleware/Localization/sample/Startup.cs index 7b6dd5c4ec74..03fa12c13b9a 100644 --- a/src/Middleware/Localization/sample/Startup.cs +++ b/src/Middleware/Localization/sample/Startup.cs @@ -1,14 +1,16 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Globalization; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Localization; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; @@ -134,21 +136,25 @@ private static async System.Threading.Tasks.Task WriteCultureSelectOptions(HttpC await context.Response.WriteAsync($" "); } - public static void Main(string[] args) + public static Task Main(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .Build(); - var host = new WebHostBuilder() - .ConfigureLogging(factory => factory.AddConsole()) - .UseKestrel() - .UseConfiguration(config) - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .ConfigureLogging(factory => factory.AddConsole()) + .UseKestrel() + .UseConfiguration(config) + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs b/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs index 0b5e64f48ad8..f264be58e152 100644 --- a/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs +++ b/src/Middleware/Localization/test/FunctionalTests/LocalizationSampleTest.cs @@ -9,6 +9,7 @@ using LocalizationSample; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Localization.FunctionalTests @@ -19,8 +20,17 @@ public class LocalizationSampleTest public async Task LocalizationSampleSmokeTest() { // Arrange - var webHostBuilder = new WebHostBuilder().UseStartup(typeof(Startup)); - var testHost = new TestServer(webHostBuilder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(typeof(Startup)); + }).Build(); + + await host.StartAsync(); + + var testHost = host.GetTestServer(); var locale = "fr-FR"; var client = testHost.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, "My/Resources"); diff --git a/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs b/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs index 15b00dfacfe2..7c2cf51063e7 100644 --- a/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs +++ b/src/Middleware/Localization/test/FunctionalTests/LocalizationTest.cs @@ -8,6 +8,7 @@ using LocalizationWebsite; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Localization.FunctionalTests @@ -97,8 +98,17 @@ public Task Localization_BuilderAPIs() private async Task RunTest(Type startupType, string culture, string expected) { - var webHostBuilder = new WebHostBuilder().UseStartup(startupType); - var testHost = new TestServer(webHostBuilder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseStartup(startupType); + }).Build(); + + await host.StartAsync(); + + var testHost = host.GetTestServer(); var client = testHost.CreateClient(); var request = new HttpRequestMessage(); @@ -109,6 +119,6 @@ private async Task RunTest(Type startupType, string culture, string expected) Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(expected, await response.Content.ReadAsStringAsync()); - } + } } } diff --git a/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs index 49a40f0a248b..d1e6f789f0d0 100644 --- a/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/AcceptLanguageHeaderRequestCultureProviderTest.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.Extensions.Localization @@ -17,28 +18,35 @@ public class AcceptLanguageHeaderRequestCultureProviderTest [Fact] public async Task GetFallbackLanguage_ReturnsFirstNonNullCultureFromSupportedCultureList() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA"), - new CultureInfo("en-US") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - return Task.FromResult(0); + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA"), + new CultureInfo("en-US") + } + }); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("jp,ar-SA,en-US"); @@ -51,28 +59,35 @@ public async Task GetFallbackLanguage_ReturnsFirstNonNullCultureFromSupportedCul [Fact] public async Task GetFallbackLanguage_ReturnsFromSupportedCulture_AcceptLanguageListContainsSupportedCultures() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("fr-FR"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA"), - new CultureInfo("en-US") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - return Task.FromResult(0); + DefaultRequestCulture = new RequestCulture("fr-FR"), + SupportedCultures = new List + { + new CultureInfo("ar-SA"), + new CultureInfo("en-US") + } + }); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-GB,ar-SA,en-US"); @@ -84,28 +99,35 @@ public async Task GetFallbackLanguage_ReturnsFromSupportedCulture_AcceptLanguage [Fact] public async Task GetFallbackLanguage_ReturnsDefault_AcceptLanguageListDoesnotContainSupportedCultures() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("fr-FR"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA"), - new CultureInfo("af-ZA") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("fr-FR", requestCulture.Culture.Name); - return Task.FromResult(0); + DefaultRequestCulture = new RequestCulture("fr-FR"), + SupportedCultures = new List + { + new CultureInfo("ar-SA"), + new CultureInfo("af-ZA") + } + }); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("fr-FR", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-GB,ar-MA,en-US"); @@ -114,37 +136,44 @@ public async Task GetFallbackLanguage_ReturnsDefault_AcceptLanguageListDoesnotCo Assert.Equal(3, count); } } - + [Fact] public async Task OmitDefaultRequestCultureShouldNotThrowNullReferenceException_And_ShouldGetTheRightCulture() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-YE") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-YE") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }); + app.Run(context => { - new CultureInfo("ar-YE") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-YE", requestCulture.Culture.Name); - Assert.Equal("ar-YE", requestCulture.UICulture.Name); - return Task.FromResult(0); + Assert.Equal("ar-YE", requestCulture.Culture.Name); + Assert.Equal("ar-YE", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-GB,ar-YE,en-US"); @@ -154,4 +183,4 @@ public async Task OmitDefaultRequestCultureShouldNotThrowNullReferenceException_ } } } -} \ No newline at end of file +} diff --git a/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs index 2e11bb42cbc7..6e5bffcb3d9f 100644 --- a/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/CookieRequestCultureProviderTest.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Microsoft.Net.Http.Headers; @@ -21,38 +22,45 @@ public class CookieRequestCultureProviderTest [Fact] public async Task GetCultureInfoFromPersistentCookie() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }; + var provider = new CookieRequestCultureProvider { - new CultureInfo("ar-SA") - } - }; - var provider = new CookieRequestCultureProvider - { - CookieName = "Preferences" - }; - options.RequestCultureProviders.Insert(0, provider); + CookieName = "Preferences" + }; + options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - return Task.FromResult(0); + app.UseRequestLocalization(options); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var culture = new CultureInfo("ar-SA"); @@ -67,37 +75,44 @@ public async Task GetCultureInfoFromPersistentCookie() [Fact] public async Task GetDefaultCultureInfoIfCultureKeysAreMissingOrInvalid() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }; + var provider = new CookieRequestCultureProvider { - new CultureInfo("ar-SA") - } - }; - var provider = new CookieRequestCultureProvider - { - CookieName = "Preferences" - }; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("en-US", requestCulture.Culture.Name); - return Task.FromResult(0); + CookieName = "Preferences" + }; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("en-US", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); @@ -109,37 +124,44 @@ public async Task GetDefaultCultureInfoIfCultureKeysAreMissingOrInvalid() [Fact] public async Task GetDefaultCultureInfoIfCookieDoesNotExist() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }; + var provider = new CookieRequestCultureProvider { - new CultureInfo("ar-SA") - } - }; - var provider = new CookieRequestCultureProvider - { - CookieName = "Preferences" - }; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("en-US", requestCulture.Culture.Name); - return Task.FromResult(0); + CookieName = "Preferences" + }; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("en-US", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -153,35 +175,42 @@ public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedCultures( TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-YE") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-YE") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }; + var provider = new CookieRequestCultureProvider { - new CultureInfo("ar-YE") - } - }; - var provider = new CookieRequestCultureProvider + CookieName = "Preferences" + }; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => Task.CompletedTask); + }) + .ConfigureServices(services => { - CookieName = "Preferences" - }; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => Task.CompletedTask); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - }); + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var culture = "??"; @@ -206,35 +235,42 @@ public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedUICulture TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-YE") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-YE") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }; + var provider = new CookieRequestCultureProvider { - new CultureInfo("ar-YE") - } - }; - var provider = new CookieRequestCultureProvider + CookieName = "Preferences" + }; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => Task.CompletedTask); + }) + .ConfigureServices(services => { - CookieName = "Preferences" - }; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => Task.CompletedTask); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - }); + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var culture = "ar-YE"; @@ -251,4 +287,4 @@ public async Task RequestLocalizationMiddleware_LogsDebugForUnsupportedUICulture Assert.Equal(expectedMessage, write.State.ToString()); } } -} \ No newline at end of file +} diff --git a/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs index 2cd5cf7177fb..2f5c2fb353fd 100644 --- a/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/CustomRequestCultureProviderTest.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.Extensions.Localization @@ -19,38 +20,45 @@ public class CustomRequestCultureProviderTest [Fact] public async Task CustomRequestCultureProviderThatGetsCultureInfoFromUrl() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar") + }, + SupportedUICultures = new List + { + new CultureInfo("ar") + } + }; + options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context => { - new CultureInfo("ar") - } - }; - options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(context => - { - var culture = GetCultureInfoFromUrl(context, options.SupportedCultures); - var requestCulture = new ProviderCultureResult(culture); - return Task.FromResult(requestCulture); - })); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar", requestCulture.Culture.Name); - return Task.FromResult(0); + var culture = GetCultureInfoFromUrl(context, options.SupportedCultures); + var requestCulture = new ProviderCultureResult(culture); + return Task.FromResult(requestCulture); + })); + app.UseRequestLocalization(options); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/ar/page"); @@ -69,4 +77,4 @@ private string GetCultureInfoFromUrl(HttpContext context, IList sup return currentCulture; } } -} \ No newline at end of file +} diff --git a/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs b/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs index 9ad34e32e213..6284e1c022d4 100644 --- a/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs +++ b/src/Middleware/Localization/test/UnitTests/QueryStringRequestCultureProviderTest.cs @@ -1,4 +1,4 @@ -// Copyright (c) .NET Foundation. All rights reserved. +// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.Extensions.Localization @@ -17,32 +18,39 @@ public class QueryStringRequestCultureProviderTest [Fact] public async Task GetCultureInfoFromQueryString() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }); + app.Run(context => { - new CultureInfo("ar-YE") - } + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + Assert.Equal("ar-YE", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - Assert.Equal("ar-YE", requestCulture.UICulture.Name); - return Task.FromResult(0); - }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA&ui-culture=ar-YE"); @@ -52,24 +60,31 @@ public async Task GetCultureInfoFromQueryString() [Fact] public async Task GetDefaultCultureInfoIfCultureKeysAreMissing() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US") - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("en-US", requestCulture.Culture.Name); - Assert.Equal("en-US", requestCulture.UICulture.Name); - return Task.FromResult(0); + app.UseRequestLocalization(new RequestLocalizationOptions + { + DefaultRequestCulture = new RequestCulture("en-US") + }); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("en-US", requestCulture.Culture.Name); + Assert.Equal("en-US", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page"); @@ -79,31 +94,38 @@ public async Task GetDefaultCultureInfoIfCultureKeysAreMissing() [Fact] public async Task GetDefaultCultureInfoIfCultureIsInSupportedCultureList() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }); + app.Run(context => { - new CultureInfo("ar-SA") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("en-US", requestCulture.Culture.Name); - return Task.FromResult(0); + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("en-US", requestCulture.Culture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-XY&ui-culture=ar-SA"); @@ -113,31 +135,38 @@ public async Task GetDefaultCultureInfoIfCultureIsInSupportedCultureList() [Fact] public async Task GetDefaultCultureInfoIfUICultureIsNotInSupportedList() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }); + app.Run(context => { - new CultureInfo("ar-SA") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("en-US", requestCulture.UICulture.Name); - return Task.FromResult(0); + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("en-US", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA&ui-culture=ar-XY"); @@ -147,32 +176,39 @@ public async Task GetDefaultCultureInfoIfUICultureIsNotInSupportedList() [Fact] public async Task GetSameCultureInfoIfCultureKeyIsMissing() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }); + app.Run(context => { - new CultureInfo("ar-SA") - } - }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - Assert.Equal("ar-SA", requestCulture.UICulture.Name); - return Task.FromResult(0); + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + Assert.Equal("ar-SA", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?ui-culture=ar-SA"); @@ -182,32 +218,39 @@ public async Task GetSameCultureInfoIfCultureKeyIsMissing() [Fact] public async Task GetSameCultureInfoIfUICultureKeyIsMissing() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRequestLocalization(new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + app.UseRequestLocalization(new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-SA") + } + }); + app.Run(context => { - new CultureInfo("ar-SA") - } + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + Assert.Equal("ar-SA", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - Assert.Equal("ar-SA", requestCulture.UICulture.Name); - return Task.FromResult(0); - }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?culture=ar-SA"); @@ -217,37 +260,44 @@ public async Task GetSameCultureInfoIfUICultureKeyIsMissing() [Fact] public async Task GetCultureInfoFromQueryStringWithCustomKeys() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("ar-SA") - }, - SupportedUICultures = new List + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("ar-SA") + }, + SupportedUICultures = new List + { + new CultureInfo("ar-YE") + } + }; + var provider = new QueryStringRequestCultureProvider(); + provider.QueryStringKey = "c"; + provider.UIQueryStringKey = "uic"; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => { - new CultureInfo("ar-YE") - } - }; - var provider = new QueryStringRequestCultureProvider(); - provider.QueryStringKey = "c"; - provider.UIQueryStringKey = "uic"; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("ar-SA", requestCulture.Culture.Name); - Assert.Equal("ar-YE", requestCulture.UICulture.Name); - return Task.FromResult(0); + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("ar-SA", requestCulture.Culture.Name); + Assert.Equal("ar-YE", requestCulture.UICulture.Name); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?c=ar-SA&uic=ar-YE"); @@ -257,42 +307,49 @@ public async Task GetCultureInfoFromQueryStringWithCustomKeys() [Fact] public async Task GetTheRightCultureInfoRegardlessOfCultureNameCasing() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - var options = new RequestLocalizationOptions + webHostBuilder + .UseTestServer() + .Configure(app => { - DefaultRequestCulture = new RequestCulture("en-US"), - SupportedCultures = new List - { - new CultureInfo("FR") - }, - SupportedUICultures = new List + var options = new RequestLocalizationOptions { - new CultureInfo("FR") - } - }; - var provider = new QueryStringRequestCultureProvider(); + DefaultRequestCulture = new RequestCulture("en-US"), + SupportedCultures = new List + { + new CultureInfo("FR") + }, + SupportedUICultures = new List + { + new CultureInfo("FR") + } + }; + var provider = new QueryStringRequestCultureProvider(); - provider.QueryStringKey = "c"; - provider.UIQueryStringKey = "uic"; - options.RequestCultureProviders.Insert(0, provider); - app.UseRequestLocalization(options); - app.Run(context => - { - var requestCultureFeature = context.Features.Get(); - var requestCulture = requestCultureFeature.RequestCulture; - Assert.Equal("fr", requestCulture.Culture.ToString()); - Assert.Equal("fr", requestCulture.UICulture.ToString()); - return Task.FromResult(0); + provider.QueryStringKey = "c"; + provider.UIQueryStringKey = "uic"; + options.RequestCultureProviders.Insert(0, provider); + app.UseRequestLocalization(options); + app.Run(context => + { + var requestCultureFeature = context.Features.Get(); + var requestCulture = requestCultureFeature.RequestCulture; + Assert.Equal("fr", requestCulture.Culture.ToString()); + Assert.Equal("fr", requestCulture.UICulture.ToString()); + return Task.FromResult(0); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("/page?c=FR&uic=FR"); } } } -} \ No newline at end of file +} diff --git a/src/Middleware/Localization/testassets/LocalizationWebsite/Program.cs b/src/Middleware/Localization/testassets/LocalizationWebsite/Program.cs index 7975594760bd..d736d118654f 100644 --- a/src/Middleware/Localization/testassets/LocalizationWebsite/Program.cs +++ b/src/Middleware/Localization/testassets/LocalizationWebsite/Program.cs @@ -1,32 +1,38 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace LocalizationWebsite { public static class Program { - public static void Main(string[] args) + public static Task Main(string[] args) { var config = new ConfigurationBuilder() .AddCommandLine(args) .Build(); - var host = new WebHostBuilder() - .ConfigureLogging((_, factory) => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.AddConsole(); - factory.AddFilter("Console", level => level >= LogLevel.Warning); + webHostBuilder + .ConfigureLogging((_, factory) => + { + factory.AddConsole(); + factory.AddFilter("Console", level => level >= LogLevel.Warning); + }) + .UseKestrel() + .UseConfiguration(config) + .UseStartup("LocalizationWebsite"); }) - .UseKestrel() - .UseConfiguration(config) - .UseStartup("LocalizationWebsite") .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs b/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs index 8f8d950a47a5..de7ff66d1c41 100644 --- a/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs +++ b/src/Middleware/MiddlewareAnalysis/samples/MiddlewareAnalysisSample/Startup.cs @@ -1,10 +1,12 @@ using System; using System.Diagnostics; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DiagnosticAdapter; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace MiddlewareAnaysisSample @@ -79,20 +81,23 @@ public void Configure(IApplicationBuilder app, ILoggerFactory factory, Diagnosti // Note there's always a default 404 middleware at the end of the pipeline. } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .ConfigureLogging((_, factory) => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.AddConsole(); - factory.AddFilter("Console", level => level >= LogLevel.Debug); - }) - .UseKestrel() - .UseIISIntegration() - .UseStartup() - .Build(); - - host.Run(); + webHostBuilder + .ConfigureLogging((_, factory) => + { + factory.AddConsole(); + factory.AddFilter("Console", level => level >= LogLevel.Debug); + }) + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }).Build(); + + return host.RunAsync(); } public class TestDiagnosticListener diff --git a/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs b/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs index 64d14ad49258..4bf4f4eaab69 100644 --- a/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs +++ b/src/Middleware/MiddlewareAnalysis/test/MiddlewareAnalysisTests.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.MiddlewareAnalysis @@ -19,23 +20,31 @@ public async Task ExceptionWrittenToDiagnostics() { DiagnosticListener diagnosticListener = null; - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - diagnosticListener = app.ApplicationServices.GetRequiredService(); - - app.UseDeveloperExceptionPage(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - throw new Exception("Test exception"); - }); - }) - .ConfigureServices(services => services.AddMiddlewareAnalysis()); - var server = new TestServer(builder); + diagnosticListener = app.ApplicationServices.GetRequiredService(); + + app.UseDeveloperExceptionPage(); + app.Run(context => + { + throw new Exception("Test exception"); + }); + }) + .ConfigureServices(services => services.AddMiddlewareAnalysis()); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var listener = new TestDiagnosticListener(); diagnosticListener.SubscribeWithAdapter(listener); - + await server.CreateClient().GetAsync(string.Empty); // "Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware", diff --git a/src/Middleware/NodeServices/samples/NodeServicesExamples/Startup.cs b/src/Middleware/NodeServices/samples/NodeServicesExamples/Startup.cs index 60cb8044e15f..44e7411132f0 100644 --- a/src/Middleware/NodeServices/samples/NodeServicesExamples/Startup.cs +++ b/src/Middleware/NodeServices/samples/NodeServicesExamples/Startup.cs @@ -3,11 +3,13 @@ using System; using System.IO; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.NodeServices; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace NodeServicesExamples @@ -58,21 +60,24 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, INodeSer } #pragma warning restore 0618 - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .ConfigureLogging(factory => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.AddConsole(); - factory.AddDebug(); - }) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseKestrel() - .UseStartup() - .Build(); + webHostBuilder + .ConfigureLogging(factory => + { + factory.AddConsole(); + factory.AddDebug(); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseKestrel() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/ResponseCaching/samples/ResponseCachingSample/Startup.cs b/src/Middleware/ResponseCaching/samples/ResponseCachingSample/Startup.cs index 6184a36946cc..3d691a3db4f0 100644 --- a/src/Middleware/ResponseCaching/samples/ResponseCachingSample/Startup.cs +++ b/src/Middleware/ResponseCaching/samples/ResponseCachingSample/Startup.cs @@ -3,10 +3,12 @@ using System; using System.IO; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Net.Http.Headers; namespace ResponseCachingSample @@ -34,16 +36,19 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseStartup() - .Build(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs b/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs index 522b6952c279..9a56152b8651 100644 --- a/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs +++ b/src/Middleware/ResponseCaching/test/ResponseCachingTests.cs @@ -22,7 +22,11 @@ public async Task ServesCachedContent_IfAvailable(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(TestUtils.CreateRequest(method, "")); @@ -42,7 +46,11 @@ public async Task ServesFreshContent_IfNotAvailable(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(TestUtils.CreateRequest(method, "")); @@ -60,7 +68,11 @@ public async Task ServesFreshContent_Post() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.PostAsync("", new StringContent(string.Empty)); @@ -78,7 +90,11 @@ public async Task ServesFreshContent_Head_Get() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var subsequentResponse = await client.SendAsync(new HttpRequestMessage(HttpMethod.Head, "")); @@ -96,7 +112,11 @@ public async Task ServesFreshContent_Get_Head() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "")); @@ -116,7 +136,11 @@ public async Task ServesFreshContent_If_CacheControlNoCache(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); @@ -145,7 +169,11 @@ public async Task ServesFreshContent_If_PragmaNoCache(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); @@ -174,7 +202,11 @@ public async Task ServesCachedContent_If_PathCasingDiffers(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(TestUtils.CreateRequest(method, "path")); @@ -194,7 +226,11 @@ public async Task ServesFreshContent_If_ResponseExpired(string method) foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(TestUtils.CreateRequest(method, "?Expires=0")); @@ -214,7 +250,11 @@ public async Task ServesFreshContent_If_Authorization_HeaderExists(string method foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("abc"); @@ -233,7 +273,11 @@ public async Task ServesCachedContent_IfVaryHeader_Matches() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.From = "user@example.com"; @@ -252,7 +296,11 @@ public async Task ServesFreshContent_IfVaryHeader_Mismatches() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.From = "user@example.com"; @@ -272,7 +320,11 @@ public async Task ServesCachedContent_IfVaryQueryKeys_Matches() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?query=value"); @@ -290,7 +342,11 @@ public async Task ServesCachedContent_IfVaryQueryKeysExplicit_Matches_QueryKeyCa foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?querya=valuea&queryb=valueb"); @@ -308,7 +364,11 @@ public async Task ServesCachedContent_IfVaryQueryKeyStar_Matches_QueryKeyCaseIns foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?querya=valuea&queryb=valueb"); @@ -326,7 +386,11 @@ public async Task ServesCachedContent_IfVaryQueryKeyExplicit_Matches_OrderInsens foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?QueryA=ValueA&QueryB=ValueB"); @@ -344,7 +408,11 @@ public async Task ServesCachedContent_IfVaryQueryKeyStar_Matches_OrderInsensitiv foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?QueryA=ValueA&QueryB=ValueB"); @@ -362,7 +430,11 @@ public async Task ServesFreshContent_IfVaryQueryKey_Mismatches() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?query=value"); @@ -380,7 +452,11 @@ public async Task ServesFreshContent_IfVaryQueryKeyExplicit_Mismatch_QueryKeyCas foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?querya=valuea&queryb=valueb"); @@ -398,7 +474,11 @@ public async Task ServesFreshContent_IfVaryQueryKeyStar_Mismatch_QueryKeyValueCa foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?querya=valuea&queryb=valueb"); @@ -416,7 +496,11 @@ public async Task ServesFreshContent_IfRequestRequirements_NotMet() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -438,7 +522,11 @@ public async Task Serves504_IfOnlyIfCachedHeader_IsSpecified() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -461,7 +549,11 @@ public async Task ServesFreshContent_IfSetCookie_IsSpecified() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -479,7 +571,11 @@ public async Task ServesCachedContent_IfSubsequentRequestContainsNoStore() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -501,7 +597,11 @@ public async Task ServesFreshContent_IfInitialRequestContainsNoStore() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue() @@ -523,7 +623,11 @@ public async Task ServesFreshContent_IfInitialResponseContainsNoStore() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -546,7 +650,11 @@ public async Task Serves304_IfIfModifiedSince_Satisfied() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?Expires=90"); @@ -567,7 +675,11 @@ public async Task ServesCachedContent_IfIfModifiedSince_NotSatisfied() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -591,7 +703,11 @@ public async Task Serves304_IfIfNoneMatch_Satisfied() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("?Expires=90"); @@ -612,7 +728,11 @@ public async Task ServesCachedContent_IfIfNoneMatch_NotSatisfied() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -634,7 +754,11 @@ public async Task ServesCachedContent_IfBodySize_IsCacheable() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -655,7 +779,11 @@ public async Task ServesFreshContent_IfBodySize_IsNotCacheable() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync(""); @@ -676,7 +804,11 @@ public async Task ServesFreshContent_CaseSensitivePaths_IsNotCacheable() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.GetAsync("/path"); @@ -694,7 +826,11 @@ public async Task ServesCachedContent_WithoutReplacingCachedVaryBy_OnCacheMiss() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.From = "user@example.com"; @@ -716,7 +852,11 @@ public async Task ServesFreshContent_IfCachedVaryByUpdated_OnCacheMiss() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.From = "user@example.com"; @@ -747,7 +887,11 @@ public async Task ServesCachedContent_IfCachedVaryByNotUpdated_OnCacheMiss() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); client.DefaultRequestHeaders.From = "user@example.com"; @@ -778,7 +922,11 @@ public async Task ServesCachedContent_IfAvailable_UsingHead_WithContentLength() foreach (var builder in builders) { - using (var server = new TestServer(builder)) + using var host = builder.Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var initialResponse = await client.SendAsync(TestUtils.CreateRequest("HEAD", "?contentLength=10")); diff --git a/src/Middleware/ResponseCaching/test/TestUtils.cs b/src/Middleware/ResponseCaching/test/TestUtils.cs index 270778f99619..1fb815ff1de7 100644 --- a/src/Middleware/ResponseCaching/test/TestUtils.cs +++ b/src/Middleware/ResponseCaching/test/TestUtils.cs @@ -12,7 +12,9 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Testing; @@ -116,7 +118,7 @@ internal static IResponseCachingKeyProvider CreateTestKeyProvider(ResponseCachin return new ResponseCachingKeyProvider(new DefaultObjectPoolProvider(), Options.Create(options)); } - internal static IEnumerable CreateBuildersWithResponseCaching( + internal static IEnumerable CreateBuildersWithResponseCaching( Action configureDelegate = null, ResponseCachingOptions options = null, Action contextAction = null) @@ -141,7 +143,7 @@ internal static IEnumerable CreateBuildersWithResponseCaching( }); } - private static IEnumerable CreateBuildersWithResponseCaching( + private static IEnumerable CreateBuildersWithResponseCaching( Action configureDelegate = null, ResponseCachingOptions options = null, IEnumerable requestDelegates = null) @@ -162,24 +164,29 @@ private static IEnumerable CreateBuildersWithResponseCaching( foreach (var requestDelegate in requestDelegates) { // Test with in memory ResponseCache - yield return new WebHostBuilder() - .ConfigureServices(services => + yield return new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCaching(responseCachingOptions => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - if (options != null) + services.AddResponseCaching(responseCachingOptions => { - responseCachingOptions.MaximumBodySize = options.MaximumBodySize; - responseCachingOptions.UseCaseSensitivePaths = options.UseCaseSensitivePaths; - responseCachingOptions.SystemClock = options.SystemClock; - } + if (options != null) + { + responseCachingOptions.MaximumBodySize = options.MaximumBodySize; + responseCachingOptions.UseCaseSensitivePaths = options.UseCaseSensitivePaths; + responseCachingOptions.SystemClock = options.SystemClock; + } + }); + }) + .Configure(app => + { + configureDelegate(app); + app.UseResponseCaching(); + app.Run(requestDelegate); }); - }) - .Configure(app => - { - configureDelegate(app); - app.UseResponseCaching(); - app.Run(requestDelegate); }); } } diff --git a/src/Middleware/ResponseCompression/sample/Startup.cs b/src/Middleware/ResponseCompression/sample/Startup.cs index a640867559b8..5d84f952d0df 100644 --- a/src/Middleware/ResponseCompression/sample/Startup.cs +++ b/src/Middleware/ResponseCompression/sample/Startup.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.ResponseCompression; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace ResponseCompressionSample @@ -71,19 +72,22 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .ConfigureLogging(factory => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.AddConsole() - .SetMinimumLevel(LogLevel.Debug); - }) - .UseStartup() - .Build(); + webHostBuilder + .UseKestrel() + .ConfigureLogging(factory => + { + factory.AddConsole() + .SetMinimumLevel(LogLevel.Debug); + }) + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs index c6ad14a66c13..ee04190af9f1 100644 --- a/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs +++ b/src/Middleware/ResponseCompression/test/ResponseCompressionMiddlewareTest.cs @@ -17,6 +17,7 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Microsoft.Net.Http.Headers; @@ -134,24 +135,31 @@ public async Task ContentType_WithCharset_Compress(string contentType) [Fact] public async Task GZipCompressionProvider_OptionsSetInDI_Compress() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.Configure(options => options.Level = CompressionLevel.NoCompression); - services.AddResponseCompression(); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.Configure(options => options.Level = CompressionLevel.NoCompression); + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - return context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + return context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -286,23 +294,30 @@ public async Task NoIncludedMimeTypes_UseDefaults() [InlineData("text/plain2")] public async Task NoBody_NotCompressed(string contentType) { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseResponseCompression(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = contentType; - return Task.FromResult(0); + app.UseResponseCompression(); + app.Run(context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = contentType; + return Task.FromResult(0); + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -413,30 +428,35 @@ public async Task Request_Https_CompressedIfEnabled(bool enableHttps, int expect TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - services.AddResponseCompression(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.EnableForHttps = enableHttps; - options.MimeTypes = new[] { TextPlain }; - }); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(context => + services.AddSingleton(loggerFactory); + services.AddResponseCompression(options => + { + options.EnableForHttps = enableHttps; + options.MimeTypes = new[] { TextPlain }; + }); + }) + .Configure(app => { - context.Response.ContentType = TextPlain; - return context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(context => + { + context.Response.ContentType = TextPlain; + return context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); - var server = new TestServer(builder) - { - BaseAddress = new Uri("https://localhost/") - }; + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("https://localhost/"); var client = server.CreateClient(); @@ -469,32 +489,37 @@ public async Task Request_Https_CompressedIfOptIn(HttpsCompressionMode mode, int TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - services.AddResponseCompression(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.EnableForHttps = false; - options.MimeTypes = new[] { TextPlain }; - }); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(context => + services.AddSingleton(loggerFactory); + services.AddResponseCompression(options => + { + options.EnableForHttps = false; + options.MimeTypes = new[] { TextPlain }; + }); + }) + .Configure(app => { - var feature = context.Features.Get(); - feature.Mode = mode; - context.Response.ContentType = TextPlain; - return context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(context => + { + var feature = context.Features.Get(); + feature.Mode = mode; + context.Response.ContentType = TextPlain; + return context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); - var server = new TestServer(builder) - { - BaseAddress = new Uri("https://localhost/") - }; + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("https://localhost/"); var client = server.CreateClient(); @@ -527,32 +552,37 @@ public async Task Request_Https_NotCompressedIfOptOut(HttpsCompressionMode mode, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddSingleton(loggerFactory); - services.AddResponseCompression(options => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - options.EnableForHttps = true; - options.MimeTypes = new[] { TextPlain }; - }); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(context => + services.AddSingleton(loggerFactory); + services.AddResponseCompression(options => + { + options.EnableForHttps = true; + options.MimeTypes = new[] { TextPlain }; + }); + }) + .Configure(app => { - var feature = context.Features.Get(); - feature.Mode = mode; - context.Response.ContentType = TextPlain; - return context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(context => + { + var feature = context.Features.Get(); + feature.Mode = mode; + context.Response.ContentType = TextPlain; + return context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); - var server = new TestServer(builder) - { - BaseAddress = new Uri("https://localhost/") - }; + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("https://localhost/"); var client = server.CreateClient(); @@ -580,28 +610,33 @@ public async Task FlushHeaders_SendsHeaders_Compresses(string encoding, int expe { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCompression(); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - context.Response.Body.Flush(); - await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - await context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(async context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + context.Response.Body.Flush(); + await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + await context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); - var server = new TestServer(builder) - { - AllowSynchronousIO = true // needed for synchronous flush - }; + await host.StartAsync(); + + var server = host.GetTestServer(); + server.AllowSynchronousIO = true; // needed for synchronous flush var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -621,25 +656,32 @@ public async Task FlushAsyncHeaders_SendsHeaders_Compresses(string encoding, int { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCompression(); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - await context.Response.Body.FlushAsync(); - await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - await context.Response.WriteAsync(new string('a', 100)); + app.UseResponseCompression(); + app.Run(async context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + await context.Response.Body.FlushAsync(); + await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + await context.Response.WriteAsync(new string('a', 100)); + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -659,32 +701,39 @@ public async Task FlushBody_CompressesAndFlushes(string encoding) { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddResponseCompression(); + }) + .Configure(app => { - var feature = context.Features.Get(); - if (feature != null) + app.UseResponseCompression(); + app.Run(async context => { - feature.AllowSynchronousIO = true; - } - - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - context.Response.Body.Write(new byte[10], 0, 10); - context.Response.Body.Flush(); - await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - context.Response.Body.Write(new byte[90], 0, 90); + var feature = context.Features.Get(); + if (feature != null) + { + feature.AllowSynchronousIO = true; + } + + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + context.Response.Body.Write(new byte[10], 0, 10); + context.Response.Body.Flush(); + await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + context.Response.Body.Write(new byte[90], 0, 90); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -711,26 +760,33 @@ public async Task FlushAsyncBody_CompressesAndFlushes(string encoding) { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCompression(); - }) - .Configure(app => - { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - await context.Response.WriteAsync(new string('a', 10)); - await context.Response.Body.FlushAsync(); - await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - await context.Response.WriteAsync(new string('a', 90)); + app.UseResponseCompression(); + app.Run(async context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + await context.Response.WriteAsync(new string('a', 10)); + await context.Response.Body.FlushAsync(); + await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + await context.Response.WriteAsync(new string('a', 90)); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -764,36 +820,43 @@ public async Task TrickleWriteAndFlush_FlushesEachWrite(string encoding) new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously), }; - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - context.Features.Get().DisableBuffering(); - - var feature = context.Features.Get(); - if (feature != null) - { - feature.AllowSynchronousIO = true; - } - - foreach (var signal in responseReceived) + services.AddResponseCompression(); + }) + .Configure(app => + { + app.UseResponseCompression(); + app.Run(async context => { - context.Response.Body.Write(new byte[1], 0, 1); - context.Response.Body.Flush(); - await signal.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - } + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + context.Features.Get().DisableBuffering(); + + var feature = context.Features.Get(); + if (feature != null) + { + feature.AllowSynchronousIO = true; + } + + foreach (var signal in responseReceived) + { + context.Response.Body.Write(new byte[1], 0, 1); + context.Response.Body.Flush(); + await signal.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + } + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -827,30 +890,37 @@ public async Task TrickleWriteAndFlushAsync_FlushesEachWrite(string encoding) new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously), }; - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseResponseCompression(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - context.Features.Get().DisableBuffering(); - - foreach (var signal in responseReceived) + services.AddResponseCompression(); + }) + .Configure(app => + { + app.UseResponseCompression(); + app.Run(async context => { - await context.Response.WriteAsync("a"); - await context.Response.Body.FlushAsync(); - await signal.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - } + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + context.Features.Get().DisableBuffering(); + + foreach (var signal in responseReceived) + { + await context.Response.WriteAsync("a"); + await context.Response.Body.FlushAsync(); + await signal.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + } + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -876,32 +946,39 @@ public async Task SendFileAsync_DifferentContentType_NotBypassed() { FakeSendFileFeature fakeSendFile = null; - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCompression(); - }) - .Configure(app => - { - app.Use((context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - fakeSendFile = new FakeSendFileFeature(context.Features.Get()); - context.Features.Set(fakeSendFile); - return next(); - }); - app.UseResponseCompression(); - app.Run(context => + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = "custom/type"; - context.Response.ContentLength = 1024; - var sendFile = context.Features.Get(); - Assert.NotNull(sendFile); - return sendFile.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + app.Use((context, next) => + { + fakeSendFile = new FakeSendFileFeature(context.Features.Get()); + context.Features.Set(fakeSendFile); + return next(); + }); + app.UseResponseCompression(); + app.Run(context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = "custom/type"; + context.Response.ContentLength = 1024; + var sendFile = context.Features.Get(); + Assert.NotNull(sendFile); + return sendFile.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -919,32 +996,39 @@ public async Task SendFileAsync_FirstWrite_CompressesAndFlushes() { FakeSendFileFeature fakeSendFile = null; - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddResponseCompression(); - }) - .Configure(app => - { - app.Use((context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - fakeSendFile = new FakeSendFileFeature(context.Features.Get()); - context.Features.Set(fakeSendFile); - return next(); - }); - app.UseResponseCompression(); - app.Run(context => + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - context.Response.ContentLength = 1024; - var sendFile = context.Features.Get(); - Assert.NotNull(sendFile); - return sendFile.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + app.Use((context, next) => + { + fakeSendFile = new FakeSendFileFeature(context.Features.Get()); + context.Features.Set(fakeSendFile); + return next(); + }); + app.UseResponseCompression(); + app.Run(context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + context.Response.ContentLength = 1024; + var sendFile = context.Features.Get(); + Assert.NotNull(sendFile); + return sendFile.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -962,32 +1046,39 @@ public async Task SendFileAsync_AfterFirstWrite_CompressesAndFlushes() { FakeSendFileFeature fakeSendFile = null; - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use((context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - fakeSendFile = new FakeSendFileFeature(context.Features.Get()); - context.Features.Set(fakeSendFile); - return next(); - }); - app.UseResponseCompression(); - app.Run(async context => + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - var feature = context.Features.Get(); + app.Use((context, next) => + { + fakeSendFile = new FakeSendFileFeature(context.Features.Get()); + context.Features.Set(fakeSendFile); + return next(); + }); + app.UseResponseCompression(); + app.Run(async context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + var feature = context.Features.Get(); - await context.Response.WriteAsync(new string('a', 100)); - await feature.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + await context.Response.WriteAsync(new string('a', 100)); + await feature.SendFileAsync("testfile1kb.txt", 0, null, CancellationToken.None); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -1006,31 +1097,38 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) { var responseReceived = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use((context, next) => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - context.Response.Body = new NoSyncWrapperStream(context.Response.Body); - return next(); - }); - app.UseResponseCompression(); - app.Run(async context => + services.AddResponseCompression(); + }) + .Configure(app => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = TextPlain; - await context.Response.WriteAsync(new string('a', 10)); - await context.Response.Body.FlushAsync(); - await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); - await context.Response.WriteAsync(new string('a', 90)); + app.Use((context, next) => + { + context.Response.Body = new NoSyncWrapperStream(context.Response.Body); + return next(); + }); + app.UseResponseCompression(); + app.Run(async context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = TextPlain; + await context.Response.WriteAsync(new string('a', 10)); + await context.Response.Body.FlushAsync(); + await responseReceived.Task.TimeoutAfter(TimeSpan.FromSeconds(3)); + await context.Response.WriteAsync(new string('a', 90)); + }); }); - }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder); + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -1063,25 +1161,32 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.AddResponseCompression(configure ?? (_ => { })); - services.AddSingleton(loggerFactory); - }) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseResponseCompression(); - app.Run(context => + webHostBuilder + .UseTestServer() + .ConfigureServices(services => { - context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; - context.Response.ContentType = responseType; - addResponseAction?.Invoke(context.Response); - return context.Response.WriteAsync(new string('a', uncompressedBodyLength)); + services.AddResponseCompression(configure ?? (_ => { })); + services.AddSingleton(loggerFactory); + }) + .Configure(app => + { + app.UseResponseCompression(); + app.Run(context => + { + context.Response.Headers[HeaderNames.ContentMD5] = "MD5"; + context.Response.ContentType = responseType; + addResponseAction?.Invoke(context.Response); + return context.Response.WriteAsync(new string('a', uncompressedBodyLength)); + }); }); - }); + }).Build(); - var server = new TestServer(builder); + await host.StartAsync(); + + var server = host.GetTestServer(); var client = server.CreateClient(); var request = new HttpRequestMessage(HttpMethod.Get, ""); @@ -1090,7 +1195,9 @@ public async Task Dispose_SyncWriteOrFlushNotCalled(string encoding) request.Headers.AcceptEncoding.Add(System.Net.Http.Headers.StringWithQualityHeaderValue.Parse(requestAcceptEncodings[i])); } - return (await client.SendAsync(request), sink.Writes.ToList()); + var response = await client.SendAsync(request); + + return (response, sink.Writes.ToList()); } private void CheckResponseCompressed(HttpResponseMessage response, int expectedBodyLength, string expectedEncoding) diff --git a/src/Middleware/Rewrite/sample/Startup.cs b/src/Middleware/Rewrite/sample/Startup.cs index 5a50edd9d805..253f0247c88c 100644 --- a/src/Middleware/Rewrite/sample/Startup.cs +++ b/src/Middleware/Rewrite/sample/Startup.cs @@ -3,11 +3,13 @@ using System.IO; using System.Net; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Rewrite; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace RewriteSample { @@ -42,23 +44,26 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel(options => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.Listen(IPAddress.Loopback, 5000); - options.Listen(IPAddress.Loopback, 5001, listenOptions => + webHostBuilder + .UseKestrel(options => { - // Configure SSL - listenOptions.UseHttps("testCert.pfx", "testPassword"); - }); - }) - .UseStartup() - .UseContentRoot(Directory.GetCurrentDirectory()) - .Build(); + options.Listen(IPAddress.Loopback, 5000); + options.Listen(IPAddress.Loopback, 5001, listenOptions => + { + // Configure SSL + listenOptions.UseHttps("testCert.pfx", "testPassword"); + }); + }) + .UseStartup() + .UseContentRoot(Directory.GetCurrentDirectory()); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs b/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs index 67deba236d44..003d5f5f993d 100644 --- a/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs +++ b/src/Middleware/Rewrite/test/ApacheModRewrite/ModRewriteMiddlewareTest.cs @@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Rewrite.Tests.ModRewrite @@ -19,13 +20,21 @@ public class ModRewriteMiddlewareTest public async Task Invoke_RewritePathWhenMatching() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("RewriteRule /hey/(.*) /$1 ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("/hey/hello"); @@ -37,13 +46,21 @@ public async Task Invoke_RewritePathTerminatesOnFirstSuccessOfRule() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("RewriteRule /hey/(.*) /$1 [L]")) .AddApacheModRewrite(new StringReader("RewriteRule /hello /what")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("/hey/hello"); @@ -55,13 +72,21 @@ public async Task Invoke_RewritePathDoesNotTerminateOnFirstSuccessOfRule() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("RewriteRule /hey/(.*) /$1")) .AddApacheModRewrite(new StringReader("RewriteRule /hello /what")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("/hey/hello"); @@ -72,13 +97,21 @@ public async Task Invoke_RewritePathDoesNotTerminateOnFirstSuccessOfRule() public async Task Invoke_ShouldIgnoreComments() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader("#RewriteRule ^/hey/(.*) /$1 ")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("/hey/hello"); @@ -89,13 +122,21 @@ public async Task Invoke_ShouldIgnoreComments() public async Task Invoke_ShouldRewriteHomepage() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule ^/$ /homepage.html")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org/"); @@ -106,13 +147,21 @@ public async Task Invoke_ShouldRewriteHomepage() public async Task Invoke_ShouldIgnorePorts() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule ^/$ /homepage.html")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org:42/"); @@ -123,13 +172,21 @@ public async Task Invoke_ShouldIgnorePorts() public async Task Invoke_HandleNegatedRewriteRules() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule !^/$ /homepage.html")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org/"); @@ -142,13 +199,21 @@ public async Task Invoke_HandleNegatedRewriteRules() public async Task Invoke_BackReferencesShouldBeApplied(string url, string rule, string expected) { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(rule)); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(url); @@ -165,13 +230,21 @@ public async Task Invoke_BackReferencesShouldBeApplied(string url, string rule, public async Task Invoke_ShouldHandleFlagNoCase(string url, string rule, string expected) { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(rule)); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(url); @@ -183,13 +256,21 @@ public async Task Invoke_CheckFullUrlWithOnlyPath() { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader(@"RewriteRule (.+) http://www.example.com$1/")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org/blog/2016-jun"); @@ -201,13 +282,21 @@ public async Task Invoke_CheckFullUrlWithUFlag() { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader(@"RewriteRule (.+) http://www.example.com$1/")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org/blog/2016-jun"); @@ -219,13 +308,21 @@ public async Task Invoke_CheckModFileConditions() { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader(@"RewriteRule (.+) http://www.example.com$1/")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("http://www.foo.org/blog/2016-jun"); @@ -238,13 +335,21 @@ public async Task Invoke_EnsureHttps(string input) { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader("RewriteCond %{REQUEST_URI} /foo/ \nRewriteCond %{HTTPS} !on \nRewriteRule ^(.*)$ https://www.example.com$1 [R=301,L]")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(input); @@ -258,13 +363,21 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRedirectLocationHasForwa { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader("RewriteRule ^(.*)$ $1 [R=301,L]")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Scheme + "://" + context.Request.Host.Host + context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(input); @@ -278,13 +391,21 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRewriteHasForwardSlash(s { var options = new RewriteOptions() .AddApacheModRewrite(new StringReader("RewriteRule ^(.*)$ $1 [L]")); - 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); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(input); Assert.Equal("/", response); @@ -294,15 +415,24 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRewriteHasForwardSlash(s public async Task Invoke_CaptureEmptyStringInRegexAssertLocationHeaderContainsPathBase() { var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteRule ^(.*)$ $1 [R=301,L]")); - 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") }; + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("http://localhost:5000/foo"); var response = await server.CreateClient().GetAsync(""); @@ -315,15 +445,24 @@ public async Task CapturedVariablesInConditionsArePreservedToRewriteRule() var options = new RewriteOptions().AddApacheModRewrite(new StringReader(@"RewriteCond %{REQUEST_URI} /home RewriteCond %{QUERY_STRING} report_id=(.+) RewriteRule (.*) http://localhost:80/home/report/%1 [R=301,L,QSD]")); - var builder = new WebHostBuilder().Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( context.Request.Path + context.Request.QueryString)); - }); + }); + }).Build(); + + await host.StartAsync(); - var server = new TestServer(builder) { BaseAddress = new Uri("http://localhost:5000/foo") }; + var server = host.GetTestServer(); + server.BaseAddress = new Uri("http://localhost:5000/foo"); var response = await server.CreateClient().GetAsync("/home?report_id=123"); Assert.Equal("http://localhost:80/home/report/123", response.Headers.Location.OriginalString); diff --git a/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs b/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs index a11410d0acc8..35e4958cb29d 100644 --- a/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs +++ b/src/Middleware/Rewrite/test/IISUrlRewrite/MiddleWareTests.cs @@ -15,6 +15,7 @@ using Microsoft.AspNetCore.Rewrite.UrlActions; using Microsoft.AspNetCore.Rewrite.UrlMatches; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; using Microsoft.Net.Http.Headers; using Xunit; @@ -33,13 +34,21 @@ public async Task Invoke_RedirectPathToPathAndQuery() ")); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Response.Headers[HeaderNames.Location])); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Response.Headers[HeaderNames.Location])); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("article/10/hey"); @@ -57,13 +66,21 @@ public async Task Invoke_RewritePathToPathAndQuery() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("/article/10/hey"); @@ -85,13 +102,21 @@ public async Task Invoke_RewriteBasedOnQueryStringParameters() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.Path + context.Request.QueryString)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.Path + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("page.asp?p2=321&p1=123"); @@ -109,13 +134,21 @@ public async Task Invoke_RedirectToLowerCase() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Response.Headers[HeaderNames.Location])); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Response.Headers[HeaderNames.Location])); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("HElLo"); @@ -137,12 +170,20 @@ public async Task Invoke_RedirectRemoveTrailingSlash() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("hey/hello/"); @@ -164,12 +205,20 @@ public async Task Invoke_RedirectAddTrailingSlash() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("hey/hello"); @@ -190,12 +239,20 @@ public async Task Invoke_RedirectToHttps() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("http://example.com")); @@ -216,18 +273,26 @@ public async Task Invoke_RewriteToHttps() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - 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); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Scheme + + "://" + + context.Request.Host + + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(new Uri("http://example.com")); @@ -245,18 +310,26 @@ public async Task Invoke_ReverseProxyToAnotherSite() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - 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); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Scheme + + "://" + + context.Request.Host + + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(new Uri("http://example.com/")); @@ -274,18 +347,26 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRedirectLocationHasForwa ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - 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); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Scheme + + "://" + + context.Request.Host + + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("http://example.com/")); @@ -303,15 +384,23 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertRewriteLocationHasForwar ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync( - context.Request.Path + - context.Request.QueryString)); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(new Uri("http://example.com/")); @@ -329,15 +418,24 @@ public async Task Invoke_CaptureEmptyStringInRegexAssertLocationHeaderContainsPa ")); - 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") }; + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("http://localhost:5000/foo"); var response = await server.CreateClient().GetAsync(""); @@ -362,12 +460,20 @@ public async Task VerifyIsFileAndIsDirectoryParsing(string matchType) ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("hey/hello"); @@ -390,12 +496,20 @@ public async Task VerifyTrackAllCaptures() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("article/23?p1=123&p2=abc"); @@ -418,12 +532,20 @@ public async Task VerifyTrackAllCapturesRuleAndConditionCapture() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("article/23?p1=123&p2=abc"); @@ -447,12 +569,20 @@ public async Task ThrowIndexOutOfRangeExceptionWithCorrectMessage() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var ex = await Assert.ThrowsAsync(() => server.CreateClient().GetAsync("article/23?p1=123&p2=abc")); @@ -475,13 +605,21 @@ public async Task Invoke_GlobalRuleConditionMatchesAgainstFullUri_ParsedRule() "; var options = new RewriteOptions().AddIISUrlRewrite(new StringReader(xml)); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // act var response = await server.CreateClient().GetStringAsync($"http://localhost/{Guid.NewGuid()}/foo/bar"); @@ -512,13 +650,21 @@ public async Task Invoke_ReverseProxyToAnotherSiteUsingXmlConfiguredRewriteMap(s ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(new Uri(requestUri)); @@ -536,12 +682,20 @@ public async Task Invoke_CustomResponse() ")); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("article/10/hey"); var content = await response.Content.ReadAsStringAsync(); @@ -583,13 +737,21 @@ public async Task Invoke_GlobalRuleConditionMatchesAgainstFullUri_CodedRule(stri ruleBuilder.AddUrlAction(action); var options = new RewriteOptions().Add(ruleBuilder.Build()); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync(context.Request.GetEncodedUrl())); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); // act var response = await server.CreateClient().GetStringAsync("http://localhost/foo/bar"); diff --git a/src/Middleware/Rewrite/test/MiddlewareTests.cs b/src/Middleware/Rewrite/test/MiddlewareTests.cs index e8a4a4aec893..21fb4bdef8f6 100644 --- a/src/Middleware/Rewrite/test/MiddlewareTests.cs +++ b/src/Middleware/Rewrite/test/MiddlewareTests.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Xunit; namespace Microsoft.AspNetCore.Rewrite.Tests.CodeRules @@ -18,18 +19,26 @@ public class MiddlewareTests public async Task CheckRewritePath() { var options = new RewriteOptions().AddRewrite("(.*)", "http://example.com/$1", skipRemainingRules: false); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - 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); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Scheme + + "://" + + context.Request.Host + + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync("foo"); @@ -40,12 +49,20 @@ public async Task CheckRewritePath() public async Task CheckRedirectPath() { var options = new RewriteOptions().AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("foo"); @@ -55,19 +72,27 @@ public async Task CheckRedirectPath() [Fact] public async Task RewriteRulesCanComeFromConfigureOptions() { - var builder = new WebHostBuilder() - .ConfigureServices(services => - { - services.Configure(options => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - options.AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently); - }); - }) - .Configure(app => - { - app.UseRewriter(); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .ConfigureServices(services => + { + services.Configure(options => + { + options.AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently); + }); + }) + .Configure(app => + { + app.UseRewriter(); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("foo"); @@ -78,12 +103,20 @@ public async Task RewriteRulesCanComeFromConfigureOptions() public async Task CheckRedirectPathWithQueryString() { var options = new RewriteOptions().AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("foo?bar=1"); @@ -98,12 +131,20 @@ public async Task CheckRedirectPathWithQueryString() public async Task CheckRedirectToHttps(int statusCode) { var options = new RewriteOptions().AddRedirectToHttps(statusCode: statusCode); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("http://example.com")); @@ -115,12 +156,20 @@ public async Task CheckRedirectToHttps(int statusCode) public async Task CheckPermanentRedirectToHttps() { var options = new RewriteOptions().AddRedirectToHttpsPermanent(); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("http://example.com")); @@ -134,12 +183,20 @@ public async Task CheckPermanentRedirectToHttps() public async Task CheckRedirectToHttpsWithSslPort(int sslPort, string expected) { var options = new RewriteOptions().AddRedirectToHttps(statusCode: StatusCodes.Status301MovedPermanently, sslPort: sslPort); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("http://example.com")); @@ -155,12 +212,20 @@ public async Task CheckRedirectToHttpsWithSslPort(int sslPort, string expected) public async Task CheckRedirectToWwwWithStatusCode(int statusCode) { var options = new RewriteOptions().AddRedirectToWww(statusCode: statusCode); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://example.com")); @@ -176,12 +241,20 @@ public async Task CheckRedirectToWwwWithStatusCode(int statusCode) public async Task CheckRedirectToWww(string requestUri, string redirectUri) { var options = new RewriteOptions().AddRedirectToWww(); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri(requestUri)); @@ -193,12 +266,20 @@ public async Task CheckRedirectToWww(string requestUri, string redirectUri) public async Task CheckPermanentRedirectToWww() { var options = new RewriteOptions().AddRedirectToWwwPermanent(); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://example.com")); @@ -220,12 +301,20 @@ public async Task CheckPermanentRedirectToWww() public async Task CheckNoRedirectToWww(string requestUri) { var options = new RewriteOptions().AddRedirectToWww(); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri(requestUri)); @@ -240,12 +329,20 @@ public async Task CheckNoRedirectToWww(string requestUri) public async Task CheckRedirectToNonWwwWithStatusCode(int statusCode) { var options = new RewriteOptions().AddRedirectToNonWww(statusCode: statusCode); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://www.example.com")); @@ -261,12 +358,20 @@ public async Task CheckRedirectToNonWwwWithStatusCode(int statusCode) public async Task CheckRedirectToNonWww(string requestUri, string redirectUri) { var options = new RewriteOptions().AddRedirectToNonWww(); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri(requestUri)); @@ -278,12 +383,20 @@ public async Task CheckRedirectToNonWww(string requestUri, string redirectUri) public async Task CheckPermanentRedirectToNonWww() { var options = new RewriteOptions().AddRedirectToNonWwwPermanent(); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://www.example.com")); @@ -295,12 +408,20 @@ public async Task CheckPermanentRedirectToNonWww() public async Task CheckIfEmptyStringRedirectCorrectly() { var options = new RewriteOptions().AddRedirect("(.*)", "$1", statusCode: StatusCodes.Status301MovedPermanently); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(""); Assert.Equal("/", response.Headers.Location.OriginalString); @@ -310,15 +431,23 @@ public async Task CheckIfEmptyStringRedirectCorrectly() public async Task CheckIfEmptyStringRewriteCorrectly() { var options = new RewriteOptions().AddRewrite("(.*)", "$1", skipRemainingRules: false); - 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); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetStringAsync(""); @@ -329,15 +458,24 @@ public async Task CheckIfEmptyStringRewriteCorrectly() 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") }; + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + app.Run(context => context.Response.WriteAsync( + context.Request.Path + + context.Request.QueryString)); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); + server.BaseAddress = new Uri("http://localhost:5000/foo"); var response = await server.CreateClient().GetAsync(""); @@ -353,12 +491,20 @@ public async Task SettingPathBase() public async Task CheckNoRedirectToWwwInNonWhitelistedDomains(string requestUri) { var options = new RewriteOptions().AddRedirectToWww("example2.com"); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri(requestUri)); @@ -373,12 +519,20 @@ public async Task CheckNoRedirectToWwwInNonWhitelistedDomains(string requestUri) public async Task CheckRedirectToWwwInWhitelistedDomains(string requestUri, string redirectUri) { var options = new RewriteOptions().AddRedirectToWww("example.com"); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri(requestUri)); @@ -390,12 +544,20 @@ public async Task CheckRedirectToWwwInWhitelistedDomains(string requestUri, stri public async Task CheckPermanentRedirectToWwwInWhitelistedDomains() { var options = new RewriteOptions().AddRedirectToWwwPermanent("example.com"); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://example.com")); @@ -411,12 +573,20 @@ public async Task CheckPermanentRedirectToWwwInWhitelistedDomains() public async Task CheckRedirectToWwwWithStatusCodeInWhitelistedDomains(int statusCode) { var options = new RewriteOptions().AddRedirectToWww(statusCode: statusCode, "example.com"); - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseRewriter(options); - }); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseRewriter(options); + }); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(new Uri("https://example.com")); diff --git a/src/Middleware/Session/samples/Startup.cs b/src/Middleware/Session/samples/Startup.cs index 9bc4265dafa1..c440f6e9b1fd 100644 --- a/src/Middleware/Session/samples/Startup.cs +++ b/src/Middleware/Session/samples/Startup.cs @@ -2,10 +2,12 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace SessionSample @@ -81,16 +83,19 @@ public void Configure(IApplicationBuilder app) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .ConfigureLogging(factory => factory.AddConsole()) - .UseKestrel() - .UseIISIntegration() - .UseStartup() - .Build(); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .ConfigureLogging(factory => factory.AddConsole()) + .UseKestrel() + .UseIISIntegration() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/Session/test/SessionTests.cs b/src/Middleware/Session/test/SessionTests.cs index 1b0a55e4474c..1a31e37d38d7 100644 --- a/src/Middleware/Session/test/SessionTests.cs +++ b/src/Middleware/Session/test/SessionTests.cs @@ -14,6 +14,7 @@ using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Internal; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -29,24 +30,31 @@ public class SessionTests [Fact] public async Task ReadingEmptySessionDoesNotCreateCookie() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseSession(); - app.Run(context => + app.Run(context => + { + Assert.Null(context.Session.GetString("NotFound")); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - Assert.Null(context.Session.GetString("NotFound")); - return Task.FromResult(0); + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -58,25 +66,32 @@ public async Task ReadingEmptySessionDoesNotCreateCookie() [Fact] public async Task SettingAValueCausesTheCookieToBeCreated() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.Null(context.Session.GetString("Key")); - context.Session.SetString("Key", "Value"); - Assert.Equal("Value", context.Session.GetString("Key")); - return Task.FromResult(0); + app.UseSession(); + app.Run(context => + { + Assert.Null(context.Session.GetString("Key")); + context.Session.SetString("Key", "Value"); + Assert.Equal("Value", context.Session.GetString("Key")); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => + { + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -99,32 +114,39 @@ public async Task SecureSessionBasedOnHttpsAndSecurePolicy( string requestUri, bool shouldBeSecureOnly) { - var builder = new WebHostBuilder() - .Configure(app => - { - app.UseSession(new SessionOptions - { - Cookie = - { - Name = "TestCookie", - SecurePolicy = cookieSecurePolicy - } - }); - app.Run(context => - { - Assert.Null(context.Session.GetString("Key")); - context.Session.SetString("Key", "Value"); - Assert.Equal("Value", context.Session.GetString("Key")); - return Task.FromResult(0); - }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); - - using (var server = new TestServer(builder)) + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseSession(new SessionOptions + { + Cookie = + { + Name = "TestCookie", + SecurePolicy = cookieSecurePolicy + } + }); + app.Run(context => + { + Assert.Null(context.Session.GetString("Key")); + context.Session.SetString("Key", "Value"); + Assert.Equal("Value", context.Session.GetString("Key")); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => + { + services.AddDistributedMemoryCache(); + services.AddSession(); + }); + }).Build(); + + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(requestUri); @@ -145,30 +167,37 @@ public async Task SecureSessionBasedOnHttpsAndSecurePolicy( [Fact] public async Task SessionCanBeAccessedOnTheNextRequest() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - int? value = context.Session.GetInt32("Key"); - if (context.Request.Path == new PathString("/first")) + app.UseSession(); + app.Run(context => { - Assert.False(value.HasValue); - value = 0; - } - Assert.True(value.HasValue); - context.Session.SetInt32("Key", value.Value + 1); - return context.Response.WriteAsync(value.Value.ToString()); + int? value = context.Session.GetInt32("Key"); + if (context.Request.Path == new PathString("/first")) + { + Assert.False(value.HasValue); + value = 0; + } + Assert.True(value.HasValue); + context.Session.SetInt32("Key", value.Value + 1); + return context.Response.WriteAsync(value.Value.ToString()); + }); + }) + .ConfigureServices(services => + { + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("first"); @@ -187,41 +216,48 @@ public async Task SessionCanBeAccessedOnTheNextRequest() [Fact] public async Task RemovedItemCannotBeAccessedAgain() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - int? value = context.Session.GetInt32("Key"); - if (context.Request.Path == new PathString("/first")) - { - Assert.False(value.HasValue); - value = 0; - context.Session.SetInt32("Key", 1); - } - else if (context.Request.Path == new PathString("/second")) - { - Assert.True(value.HasValue); - Assert.Equal(1, value); - context.Session.Remove("Key"); - } - else if (context.Request.Path == new PathString("/third")) + app.UseSession(); + app.Run(context => { - Assert.False(value.HasValue); - value = 2; - } - return context.Response.WriteAsync(value.Value.ToString()); + int? value = context.Session.GetInt32("Key"); + if (context.Request.Path == new PathString("/first")) + { + Assert.False(value.HasValue); + value = 0; + context.Session.SetInt32("Key", 1); + } + else if (context.Request.Path == new PathString("/second")) + { + Assert.True(value.HasValue); + Assert.Equal(1, value); + context.Session.Remove("Key"); + } + else if (context.Request.Path == new PathString("/third")) + { + Assert.False(value.HasValue); + value = 2; + } + return context.Response.WriteAsync(value.Value.ToString()); + }); + }) + .ConfigureServices( + services => + { + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices( - services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("first"); @@ -239,40 +275,47 @@ public async Task RemovedItemCannotBeAccessedAgain() [Fact] public async Task ClearedItemsCannotBeAccessedAgain() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - int? value = context.Session.GetInt32("Key"); - if (context.Request.Path == new PathString("/first")) + app.UseSession(); + app.Run(context => { - Assert.False(value.HasValue); - value = 0; - context.Session.SetInt32("Key", 1); - } - else if (context.Request.Path == new PathString("/second")) - { - Assert.True(value.HasValue); - Assert.Equal(1, value); - context.Session.Clear(); - } - else if (context.Request.Path == new PathString("/third")) - { - Assert.False(value.HasValue); - value = 2; - } - return context.Response.WriteAsync(value.Value.ToString()); + int? value = context.Session.GetInt32("Key"); + if (context.Request.Path == new PathString("/first")) + { + Assert.False(value.HasValue); + value = 0; + context.Session.SetInt32("Key", 1); + } + else if (context.Request.Path == new PathString("/second")) + { + Assert.True(value.HasValue); + Assert.Equal(1, value); + context.Session.Clear(); + } + else if (context.Request.Path == new PathString("/third")) + { + Assert.False(value.HasValue); + value = 2; + } + return context.Response.WriteAsync(value.Value.ToString()); + }); + }) + .ConfigureServices(services => + { + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("first"); @@ -294,24 +337,31 @@ public async Task SessionStart_LogsInformation() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => + { + app.UseSession(); + app.Run(context => + { + context.Session.SetString("Key", "Value"); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - context.Session.SetString("Key", "Value"); - return Task.FromResult(0); + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -334,36 +384,43 @@ public async Task ExpiredSession_LogsInfo() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - int? value = context.Session.GetInt32("Key"); - if (context.Request.Path == new PathString("/first")) - { - Assert.False(value.HasValue); - value = 1; - context.Session.SetInt32("Key", 1); - } - else if (context.Request.Path == new PathString("/second")) + app.UseSession(); + app.Run(context => { - Assert.False(value.HasValue); - value = 2; - } - return context.Response.WriteAsync(value.Value.ToString()); + int? value = context.Session.GetInt32("Key"); + if (context.Request.Path == new PathString("/first")) + { + Assert.False(value.HasValue); + value = 1; + context.Session.SetInt32("Key", 1); + } + else if (context.Request.Path == new PathString("/second")) + { + Assert.False(value.HasValue); + value = 2; + } + return context.Response.WriteAsync(value.Value.ToString()); + }); + }) + .ConfigureServices(services => + { + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddDistributedMemoryCache(); + services.AddSession(o => o.IdleTimeout = TimeSpan.FromMilliseconds(30)); }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddDistributedMemoryCache(); - services.AddSession(o => o.IdleTimeout = TimeSpan.FromMilliseconds(30)); - }); + }).Build(); + + await host.StartAsync(); string result; - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("first"); @@ -392,40 +449,47 @@ public async Task ExpiredSession_LogsInfo() public async Task RefreshesSession_WhenSessionData_IsNotModified() { var clock = new TestClock(); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - string responseData = string.Empty; - if (context.Request.Path == new PathString("/AddDataToSession")) + app.UseSession(); + app.Run(context => { - context.Session.SetInt32("Key", 10); - responseData = "added data to session"; - } - else if (context.Request.Path == new PathString("/AccessSessionData")) - { - var value = context.Session.GetInt32("Key"); - responseData = (value == null) ? "No value found in session." : value.ToString(); - } - else if (context.Request.Path == new PathString("/DoNotAccessSessionData")) - { - responseData = "did not access session data"; - } - - return context.Response.WriteAsync(responseData); + string responseData = string.Empty; + if (context.Request.Path == new PathString("/AddDataToSession")) + { + context.Session.SetInt32("Key", 10); + responseData = "added data to session"; + } + else if (context.Request.Path == new PathString("/AccessSessionData")) + { + var value = context.Session.GetInt32("Key"); + responseData = (value == null) ? "No value found in session." : value.ToString(); + } + else if (context.Request.Path == new PathString("/DoNotAccessSessionData")) + { + responseData = "did not access session data"; + } + + return context.Response.WriteAsync(responseData); + }); + }) + .ConfigureServices(services => + { + services.AddSingleton(typeof(ILoggerFactory), NullLoggerFactory.Instance); + services.AddDistributedMemoryCache(); + services.AddSession(o => o.IdleTimeout = TimeSpan.FromMinutes(20)); + services.Configure(o => o.Clock = clock); }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), NullLoggerFactory.Instance); - services.AddDistributedMemoryCache(); - services.AddSession(o => o.IdleTimeout = TimeSpan.FromMinutes(20)); - services.Configure(o => o.Clock = clock); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync("AddDataToSession"); @@ -450,31 +514,38 @@ public async Task RefreshesSession_WhenSessionData_IsNotModified() [Fact] public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (httpContext, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - await next(); + app.Use(async (httpContext, next) => + { + await next(); - Assert.Null(httpContext.Features.Get()); - }); + Assert.Null(httpContext.Features.Get()); + }); - app.UseSession(); + app.UseSession(); - app.Run(context => + app.Run(context => + { + context.Session.SetString("key", "value"); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - context.Session.SetString("key", "value"); - return Task.FromResult(0); + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -485,39 +556,46 @@ public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut() [Fact] public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut_AndAnUnhandledExcetionIsThrown() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (httpContext, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - var exceptionThrown = false; - try + app.Use(async (httpContext, next) => { - await next(); - } - catch + var exceptionThrown = false; + try + { + await next(); + } + catch + { + exceptionThrown = true; + } + + Assert.True(exceptionThrown); + Assert.Null(httpContext.Features.Get()); + }); + + app.UseSession(); + + app.Run(context => { - exceptionThrown = true; - } - - Assert.True(exceptionThrown); - Assert.Null(httpContext.Features.Get()); - }); - - app.UseSession(); - - app.Run(context => + throw new InvalidOperationException("An error occurred."); + }); + }) + .ConfigureServices(services => { - throw new InvalidOperationException("An error occurred."); + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -527,26 +605,33 @@ public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut_AndAnUnhand [Fact] public async Task SessionKeys_AreCaseSensitive() { - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - context.Session.SetString("KEY", "VALUE"); - context.Session.SetString("key", "value"); - Assert.Equal("VALUE", context.Session.GetString("KEY")); - Assert.Equal("value", context.Session.GetString("key")); - return Task.FromResult(0); + app.UseSession(); + app.Run(context => + { + context.Session.SetString("KEY", "VALUE"); + context.Session.SetString("key", "value"); + Assert.Equal("VALUE", context.Session.GetString("KEY")); + Assert.Equal("value", context.Session.GetString("key")); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => + { + services.AddDistributedMemoryCache(); + services.AddSession(); }); - }) - .ConfigureServices(services => - { - services.AddDistributedMemoryCache(); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -561,30 +646,37 @@ public async Task SessionLogsCacheReadException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - Assert.False(context.Session.TryGetValue("key", out var value)); - Assert.Null(value); - Assert.Equal(string.Empty, context.Session.Id); - Assert.False(context.Session.Keys.Any()); - return Task.FromResult(0); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(context => + { + Assert.False(context.Session.TryGetValue("key", out var value)); + Assert.Null(value); + Assert.Equal(string.Empty, context.Session.Id); + Assert.False(context.Session.Keys.Any()); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - DisableGet = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DisableGet = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -603,29 +695,36 @@ public async Task SessionLogsCacheLoadAsyncException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - await Assert.ThrowsAsync(() => context.Session.LoadAsync()); - Assert.False(context.Session.IsAvailable); - Assert.Equal(string.Empty, context.Session.Id); - Assert.False(context.Session.Keys.Any()); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(async context => + { + await Assert.ThrowsAsync(() => context.Session.LoadAsync()); + Assert.False(context.Session.IsAvailable); + Assert.Equal(string.Empty, context.Session.Id); + Assert.False(context.Session.Keys.Any()); + }); + }) + .ConfigureServices(services => { - DisableGet = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DisableGet = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -644,29 +743,36 @@ public async Task SessionLogsCacheLoadAsyncTimeoutException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(new SessionOptions() + webHostBuilder + .UseTestServer() + .Configure(app => { - IOTimeout = TimeSpan.FromSeconds(0.5) - }); - app.Run(async context => - { - await Assert.ThrowsAsync(() => context.Session.LoadAsync()); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(new SessionOptions() + { + IOTimeout = TimeSpan.FromSeconds(0.5) + }); + app.Run(async context => + { + await Assert.ThrowsAsync(() => context.Session.LoadAsync()); + }); + }) + .ConfigureServices(services => { - DelayGetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DelayGetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -685,29 +791,36 @@ public async Task SessionLoadAsyncCanceledException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - var cts = new CancellationTokenSource(); - var token = cts.Token; - cts.Cancel(); - await Assert.ThrowsAsync(() => context.Session.LoadAsync(token)); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(async context => + { + var cts = new CancellationTokenSource(); + var token = cts.Token; + cts.Cancel(); + await Assert.ThrowsAsync(() => context.Session.LoadAsync(token)); + }); + }) + .ConfigureServices(services => { - DelayGetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DelayGetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -732,27 +845,34 @@ public async Task SessionLogsCacheCommitException() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - context.Session.SetInt32("key", 0); - return Task.FromResult(0); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(context => + { + context.Session.SetInt32("key", 0); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - DisableSetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DisableSetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); - using (var server = new TestServer(builder)) + await host.StartAsync(); + + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -785,30 +905,37 @@ public async Task SessionLogsCacheCommitTimeoutException() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(new SessionOptions() - { - IOTimeout = TimeSpan.FromSeconds(0.5) - }); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - context.Session.SetInt32("key", 0); - return Task.FromResult(0); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(new SessionOptions() + { + IOTimeout = TimeSpan.FromSeconds(0.5) + }); + app.Run(context => + { + context.Session.SetInt32("key", 0); + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - DelaySetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DelaySetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -844,30 +971,37 @@ public async Task SessionLogsCacheCommitCanceledException() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(async context => + webHostBuilder + .UseTestServer() + .Configure(app => { - context.Session.SetInt32("key", 0); - var cts = new CancellationTokenSource(); - var token = cts.Token; - cts.Cancel(); - await Assert.ThrowsAsync(() => context.Session.CommitAsync(token)); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(async context => + { + context.Session.SetInt32("key", 0); + var cts = new CancellationTokenSource(); + var token = cts.Token; + cts.Cancel(); + await Assert.ThrowsAsync(() => context.Session.CommitAsync(token)); + }); + }) + .ConfigureServices(services => { - DelaySetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DelaySetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -901,31 +1035,38 @@ public async Task RequestAbortedIgnored() || beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName); }); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - context.Session.SetInt32("key", 0); - var cts = new CancellationTokenSource(); - var token = cts.Token; - cts.Cancel(); - context.RequestAborted = token; - return Task.CompletedTask; - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(context => + { + context.Session.SetInt32("key", 0); + var cts = new CancellationTokenSource(); + var token = cts.Token; + cts.Cancel(); + context.RequestAborted = token; + return Task.CompletedTask; + }); + }) + .ConfigureServices(services => { - DelaySetAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DelaySetAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); @@ -950,27 +1091,34 @@ public async Task SessionLogsCacheRefreshException() TestSink.EnableWithTypeName, TestSink.EnableWithTypeName); var loggerFactory = new TestLoggerFactory(sink, enabled: true); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.UseSession(); - app.Run(context => + webHostBuilder + .UseTestServer() + .Configure(app => { - // The middleware calls context.Session.CommitAsync() once per request - return Task.FromResult(0); - }); - }) - .ConfigureServices(services => - { - services.AddSingleton(typeof(ILoggerFactory), loggerFactory); - services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + app.UseSession(); + app.Run(context => + { + // The middleware calls context.Session.CommitAsync() once per request + return Task.FromResult(0); + }); + }) + .ConfigureServices(services => { - DisableRefreshAsync = true + services.AddSingleton(typeof(ILoggerFactory), loggerFactory); + services.AddSingleton(new UnreliableCache(new MemoryCache(new MemoryCacheOptions())) + { + DisableRefreshAsync = true + }); + services.AddSession(); }); - services.AddSession(); - }); + }).Build(); + + await host.StartAsync(); - using (var server = new TestServer(builder)) + using (var server = host.GetTestServer()) { var client = server.CreateClient(); var response = await client.GetAsync(string.Empty); diff --git a/src/Middleware/StaticFiles/samples/StaticFileSample/Startup.cs b/src/Middleware/StaticFiles/samples/StaticFileSample/Startup.cs index b0d553e15d51..bbaea9dcd43a 100644 --- a/src/Middleware/StaticFiles/samples/StaticFileSample/Startup.cs +++ b/src/Middleware/StaticFiles/samples/StaticFileSample/Startup.cs @@ -1,8 +1,10 @@ using System; using System.IO; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace StaticFilesSample @@ -25,22 +27,25 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment host) }); } - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .ConfigureLogging(factory => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - factory.AddFilter("Console", level => level >= LogLevel.Debug); - factory.AddConsole(); - }) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseKestrel() - // .UseHttpSys() - .UseIISIntegration() - .UseStartup() - .Build(); + webHostBuilder + .ConfigureLogging(factory => + { + factory.AddFilter("Console", level => level >= LogLevel.Debug); + factory.AddConsole(); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseKestrel() + // .UseHttpSys() + .UseIISIntegration() + .UseStartup(); + }).Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs b/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs index e3c1073174bd..dff351cedf41 100644 --- a/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs +++ b/src/Middleware/StaticFiles/test/FunctionalTests/FallbackStaticFileTest.cs @@ -15,6 +15,7 @@ using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging.Testing; using Xunit; @@ -25,94 +26,102 @@ public class FallbackStaticFileTest : LoggedTest [Fact] public async Task ReturnsFileForDefaultPattern() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddRouting(); - services.AddSingleton(LoggerFactory); - }) - .UseKestrel() - .UseWebRoot(AppContext.BaseDirectory) - .Configure(app => - { - var environment = app.ApplicationServices.GetRequiredService(); - app.UseRouting(); - app.UseEndpoints(endpoints => + webHostBuilder + .ConfigureServices(services => + { + services.AddRouting(); + services.AddSingleton(LoggerFactory); + }) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .UseWebRoot(AppContext.BaseDirectory) + .Configure(app => { - endpoints.Map("/hello", context => + var environment = app.ApplicationServices.GetRequiredService(); + app.UseRouting(); + app.UseEndpoints(endpoints => { - return context.Response.WriteAsync("Hello, world!"); - }); + endpoints.Map("/hello", context => + { + return context.Response.WriteAsync("Hello, world!"); + }); - endpoints.MapFallbackToFile("default.html", new StaticFileOptions() - { - FileProvider = new PhysicalFileProvider(Path.Combine(environment.WebRootPath, "SubFolder")), + endpoints.MapFallbackToFile("default.html", new StaticFileOptions() + { + FileProvider = new PhysicalFileProvider(Path.Combine(environment.WebRootPath, "SubFolder")), + }); }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) + var environment = host.Services.GetRequiredService(); + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { - var environment = server.Services.GetRequiredService(); - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var response = await client.GetAsync("hello"); - var responseText = await response.Content.ReadAsStringAsync(); + var response = await client.GetAsync("hello"); + var responseText = await response.Content.ReadAsStringAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Hello, world!", responseText); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("Hello, world!", responseText); - response = await client.GetAsync("/"); - var responseContent = await response.Content.ReadAsByteArrayAsync(); + response = await client.GetAsync("/"); + var responseContent = await response.Content.ReadAsByteArrayAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - AssertFileEquals(environment, "SubFolder/default.html", responseContent); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + AssertFileEquals(environment, "SubFolder/default.html", responseContent); } } [Fact] public async Task ReturnsFileForCustomPattern() { - var builder = new WebHostBuilder() - .ConfigureServices(services => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - services.AddRouting(); - services.AddSingleton(LoggerFactory); - }) - .UseKestrel() - .UseWebRoot(AppContext.BaseDirectory) - .Configure(app => - { - app.UseRouting(); - app.UseEndpoints(endpoints => + webHostBuilder + .ConfigureServices(services => + { + services.AddRouting(); + services.AddSingleton(LoggerFactory); + }) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .UseWebRoot(AppContext.BaseDirectory) + .Configure(app => { - endpoints.Map("/hello", context => + app.UseRouting(); + app.UseEndpoints(endpoints => { - return context.Response.WriteAsync("Hello, world!"); - }); + endpoints.Map("/hello", context => + { + return context.Response.WriteAsync("Hello, world!"); + }); - endpoints.MapFallbackToFile("/prefix/{*path:nonfile}", "TestDocument.txt"); + endpoints.MapFallbackToFile("/prefix/{*path:nonfile}", "TestDocument.txt"); + }); }); - }); + }).Build(); + + await host.StartAsync(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) + var environment = host.Services.GetRequiredService(); + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { - var environment = server.Services.GetRequiredService(); - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var response = await client.GetAsync("hello"); - var responseText = await response.Content.ReadAsStringAsync(); + var response = await client.GetAsync("hello"); + var responseText = await response.Content.ReadAsStringAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Hello, world!", responseText); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("Hello, world!", responseText); - response = await client.GetAsync("prefix/Some-Path"); - var responseContent = await response.Content.ReadAsByteArrayAsync(); + response = await client.GetAsync("prefix/Some-Path"); + var responseContent = await response.Content.ReadAsByteArrayAsync(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - AssertFileEquals(environment, "TestDocument.txt", responseContent); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + AssertFileEquals(environment, "TestDocument.txt", responseContent); } } diff --git a/src/Middleware/StaticFiles/test/FunctionalTests/Helpers.cs b/src/Middleware/StaticFiles/test/FunctionalTests/Helpers.cs index 12e634cda156..57e0e30da5c6 100644 --- a/src/Middleware/StaticFiles/test/FunctionalTests/Helpers.cs +++ b/src/Middleware/StaticFiles/test/FunctionalTests/Helpers.cs @@ -3,15 +3,18 @@ using System.Linq; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.StaticFiles { public static class Helpers { - public static string GetAddress(IWebHost server) + public static string GetAddress(IHost server) { - return server.ServerFeatures.Get().Addresses.First(); + return server.Services.GetService().Features.Get().Addresses.First(); } } } diff --git a/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs b/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs index b4ca20cf0a5c..14183c0647f4 100644 --- a/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/FunctionalTests/StaticFileMiddlewareTests.cs @@ -18,6 +18,7 @@ using Microsoft.AspNetCore.Server.IntegrationTesting.Common; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging.Testing; using Xunit; @@ -28,84 +29,96 @@ public class StaticFileMiddlewareTests : LoggedTest [Fact] public async Task ReturnsNotFoundWithoutWwwroot() { - var builder = new WebHostBuilder() - .ConfigureServices(services => services.AddSingleton(LoggerFactory)) - .UseKestrel() - .Configure(app => app.UseStaticFiles()); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .ConfigureServices(services => services.AddSingleton(LoggerFactory)) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .Configure(app => app.UseStaticFiles()); + }).Build(); + + await host.StartAsync(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var response = await client.GetAsync("TestDocument.txt"); + var response = await client.GetAsync("TestDocument.txt"); - Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); - } + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } } [Fact] public async Task Endpoint_PassesThrough() { - var builder = new WebHostBuilder() - .ConfigureServices(services => { services.AddSingleton(LoggerFactory); services.AddRouting(); }) - .UseKestrel() - .UseWebRoot(AppContext.BaseDirectory) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - // Routing first => static files noops - app.UseRouting(); - - app.Use(next => context => + webHostBuilder + .ConfigureServices(services => { services.AddSingleton(LoggerFactory); services.AddRouting(); }) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .UseWebRoot(AppContext.BaseDirectory) + .Configure(app => { - // Assign an endpoint, this will make the default files noop. - context.SetEndpoint(new Endpoint((c) => + // Routing first => static files noops + app.UseRouting(); + + app.Use(next => context => { - return context.Response.WriteAsync("Hi from endpoint."); - }, - new EndpointMetadataCollection(), - "test")); + // Assign an endpoint, this will make the default files noop. + context.SetEndpoint(new Endpoint((c) => + { + return context.Response.WriteAsync("Hi from endpoint."); + }, + new EndpointMetadataCollection(), + "test")); - return next(context); - }); + return next(context); + }); + + app.UseStaticFiles(); - app.UseStaticFiles(); + app.UseEndpoints(endpoints => { }); + }); + }).Build(); - app.UseEndpoints(endpoints => {}); - }); + await host.StartAsync(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var response = await client.GetAsync("TestDocument.txt"); + var response = await client.GetAsync("TestDocument.txt"); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("Hi from endpoint.", await response.Content.ReadAsStringAsync()); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("Hi from endpoint.", await response.Content.ReadAsStringAsync()); } } [Fact] public async Task FoundFile_LastModifiedTrimsSeconds() { - var builder = new WebHostBuilder() - .ConfigureServices(services => services.AddSingleton(LoggerFactory)) - .UseKestrel() - .UseWebRoot(AppContext.BaseDirectory) - .Configure(app => app.UseStaticFiles()); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .ConfigureServices(services => services.AddSingleton(LoggerFactory)) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .UseWebRoot(AppContext.BaseDirectory) + .Configure(app => app.UseStaticFiles()); + }).Build(); + + await host.StartAsync(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var last = File.GetLastWriteTimeUtc(Path.Combine(AppContext.BaseDirectory, "TestDocument.txt")); - var response = await client.GetAsync("TestDocument.txt"); + var last = File.GetLastWriteTimeUtc(Path.Combine(AppContext.BaseDirectory, "TestDocument.txt")); + var response = await client.GetAsync("TestDocument.txt"); - var trimmed = new DateTimeOffset(last.Year, last.Month, last.Day, last.Hour, last.Minute, last.Second, TimeSpan.Zero).ToUniversalTime(); + var trimmed = new DateTimeOffset(last.Year, last.Month, last.Day, last.Hour, last.Minute, last.Second, TimeSpan.Zero).ToUniversalTime(); - Assert.Equal(response.Content.Headers.LastModified.Value, trimmed); - } + Assert.Equal(response.Content.Headers.LastModified.Value, trimmed); } } @@ -130,36 +143,40 @@ public async Task FoundFile_Served_Windows(string baseUrl, string baseDir, strin private async Task FoundFile_Served(string baseUrl, string baseDir, string requestUrl) { - var builder = new WebHostBuilder() - .ConfigureServices(services => services.AddSingleton(LoggerFactory)) - .UseKestrel() - .UseWebRoot(Path.Combine(AppContext.BaseDirectory, baseDir)) - .Configure(app => app.UseStaticFiles(new StaticFileOptions + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - RequestPath = new PathString(baseUrl), - })); + webHostBuilder + .ConfigureServices(services => services.AddSingleton(LoggerFactory)) + .UseKestrel() + .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) + .UseWebRoot(Path.Combine(AppContext.BaseDirectory, baseDir)) + .Configure(app => app.UseStaticFiles(new StaticFileOptions + { + RequestPath = new PathString(baseUrl), + })); + }).Build(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) - { - var hostingEnvironment = server.Services.GetService(); + await host.StartAsync(); - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var fileInfo = hostingEnvironment.WebRootFileProvider.GetFileInfo(Path.GetFileName(requestUrl)); - var response = await client.GetAsync(requestUrl); - var responseContent = await response.Content.ReadAsByteArrayAsync(); + var hostingEnvironment = host.Services.GetService(); - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); - Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); - Assert.Equal(response.Content.Headers.ContentLength, responseContent.Length); + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) + { + var fileInfo = hostingEnvironment.WebRootFileProvider.GetFileInfo(Path.GetFileName(requestUrl)); + var response = await client.GetAsync(requestUrl); + var responseContent = await response.Content.ReadAsByteArrayAsync(); - using (var stream = fileInfo.CreateReadStream()) - { - var fileContents = new byte[stream.Length]; - stream.Read(fileContents, 0, (int)stream.Length); - Assert.True(responseContent.SequenceEqual(fileContents)); - } + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); + Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); + Assert.Equal(response.Content.Headers.ContentLength, responseContent.Length); + + using (var stream = fileInfo.CreateReadStream()) + { + var fileContents = new byte[stream.Length]; + stream.Read(fileContents, 0, (int)stream.Length); + Assert.True(responseContent.SequenceEqual(fileContents)); } } } @@ -168,30 +185,33 @@ private async Task FoundFile_Served(string baseUrl, string baseDir, string reque [MemberData(nameof(ExistingFiles))] public async Task HeadFile_HeadersButNotBodyServed(string baseUrl, string baseDir, string requestUrl) { - var builder = new WebHostBuilder() - .ConfigureServices(services => services.AddSingleton(LoggerFactory)) - .UseKestrel() - .UseWebRoot(Path.Combine(AppContext.BaseDirectory, baseDir)) - .Configure(app => app.UseStaticFiles(new StaticFileOptions + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - RequestPath = new PathString(baseUrl), - })); + webHostBuilder + .ConfigureServices(services => services.AddSingleton(LoggerFactory)) + .UseKestrel() + .UseWebRoot(Path.Combine(AppContext.BaseDirectory, baseDir)) + .Configure(app => app.UseStaticFiles(new StaticFileOptions + { + RequestPath = new PathString(baseUrl), + })); + }).Build(); - using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) - { - var hostingEnvironment = server.Services.GetService(); + await host.StartAsync(); - using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(server)) }) - { - var fileInfo = hostingEnvironment.WebRootFileProvider.GetFileInfo(Path.GetFileName(requestUrl)); - var request = new HttpRequestMessage(HttpMethod.Head, requestUrl); - var response = await client.SendAsync(request); - - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); - Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); - Assert.Empty((await response.Content.ReadAsByteArrayAsync())); - } + var hostingEnvironment = host.Services.GetService(); + + using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) + { + var fileInfo = hostingEnvironment.WebRootFileProvider.GetFileInfo(Path.GetFileName(requestUrl)); + var request = new HttpRequestMessage(HttpMethod.Head, requestUrl); + var response = await client.SendAsync(request); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/plain", response.Content.Headers.ContentType.ToString()); + Assert.True(response.Content.Headers.ContentLength == fileInfo.Length); + Assert.Empty((await response.Content.ReadAsByteArrayAsync())); } } @@ -226,51 +246,55 @@ private async Task ClientDisconnect_NoWriteExceptionThrown(ServerType serverType var requestCancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var responseComplete = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); Exception exception = null; - var builder = new WebHostBuilder() - .ConfigureServices(services => services.AddSingleton(LoggerFactory)) - .UseWebRoot(Path.Combine(AppContext.BaseDirectory)) - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (context, next) => + webHostBuilder + .ConfigureServices(services => services.AddSingleton(LoggerFactory)) + .UseWebRoot(Path.Combine(AppContext.BaseDirectory)) + .Configure(app => { - try + app.Use(async (context, next) => { - requestReceived.SetResult(0); - await requestCancelled.Task.TimeoutAfter(interval); - Assert.True(context.RequestAborted.WaitHandle.WaitOne(interval), "not aborted"); - await next(); - } - catch (Exception ex) - { - exception = ex; - } - responseComplete.SetResult(0); - }); - app.UseStaticFiles(); - }); + try + { + requestReceived.SetResult(0); + await requestCancelled.Task.TimeoutAfter(interval); + Assert.True(context.RequestAborted.WaitHandle.WaitOne(interval), "not aborted"); + await next(); + } + catch (Exception ex) + { + exception = ex; + } + responseComplete.SetResult(0); + }); + app.UseStaticFiles(); + }) + .UseUrls(TestUrlHelper.GetTestUrl(serverType)); + + if (serverType == ServerType.HttpSys) + { + webHostBuilder.UseHttpSys(); + } + else if (serverType == ServerType.Kestrel) + { + webHostBuilder.UseKestrel(); + } + }).Build(); - if (serverType == ServerType.HttpSys) - { - builder.UseHttpSys(); - } - else if (serverType == ServerType.Kestrel) - { - builder.UseKestrel(); - } + await host.StartAsync(); - 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(Helpers.GetAddress(server), "/TestDocument1MB.txt"); - await requestReceived.Task.TimeoutAfter(interval); + // We don't use HttpClient here because it's disconnect behavior varies across platforms. + var socket = SendSocketRequestAsync(Helpers.GetAddress(host), "/TestDocument1MB.txt"); + await requestReceived.Task.TimeoutAfter(interval); - socket.LingerState = new LingerOption(true, 0); - socket.Dispose(); - requestCancelled.SetResult(0); + socket.LingerState = new LingerOption(true, 0); + socket.Dispose(); + requestCancelled.SetResult(0); - await responseComplete.Task.TimeoutAfter(interval); - Assert.Null(exception); - } + await responseComplete.Task.TimeoutAfter(interval); + Assert.Null(exception); } private Socket SendSocketRequestAsync(string address, string path, string method = "GET") diff --git a/src/Middleware/StaticFiles/test/UnitTests/CacheHeaderTests.cs b/src/Middleware/StaticFiles/test/UnitTests/CacheHeaderTests.cs index 7c70ce4551f7..8f02132ea0fc 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/CacheHeaderTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/CacheHeaderTests.cs @@ -18,7 +18,8 @@ public class CacheHeaderTests [Fact] public async Task ServerShouldReturnETag() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); Assert.NotNull(response.Headers.ETag); @@ -28,7 +29,8 @@ public async Task ServerShouldReturnETag() [Fact] public async Task SameETagShouldBeReturnedAgain() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage response1 = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); HttpResponseMessage response2 = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); @@ -47,7 +49,8 @@ public async Task SameETagShouldBeReturnedAgain() [MemberData(nameof(SupportedMethods))] public async Task IfMatchShouldReturn412WhenNotListed(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); req.Headers.Add("If-Match", "\"fake\""); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -58,7 +61,8 @@ public async Task IfMatchShouldReturn412WhenNotListed(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task IfMatchShouldBeServedWhenListed(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); var req = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); @@ -71,7 +75,8 @@ public async Task IfMatchShouldBeServedWhenListed(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task IfMatchShouldBeServedForAsterisk(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); req.Headers.Add("If-Match", "*"); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -82,7 +87,8 @@ public async Task IfMatchShouldBeServedForAsterisk(HttpMethod method) [MemberData(nameof(UnsupportedMethods))] public async Task IfMatchShouldBeIgnoredForUnsupportedMethods(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); req.Headers.Add("If-Match", "*"); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -107,7 +113,8 @@ public async Task IfMatchShouldBeIgnoredForUnsupportedMethods(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task IfNoneMatchShouldReturn304ForMatching(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); var req2 = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); @@ -120,7 +127,8 @@ public async Task IfNoneMatchShouldReturn304ForMatching(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task IfNoneMatchAllShouldReturn304ForMatching(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); var req2 = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); @@ -133,7 +141,8 @@ public async Task IfNoneMatchAllShouldReturn304ForMatching(HttpMethod method) [MemberData(nameof(UnsupportedMethods))] public async Task IfNoneMatchShouldBeIgnoredForNonTwoHundredAnd304Responses(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server.CreateClient().GetAsync("http://localhost/SubFolder/extra.xml"); var req2 = new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml"); @@ -156,7 +165,8 @@ public async Task IfNoneMatchShouldBeIgnoredForNonTwoHundredAnd304Responses(Http [MemberData(nameof(SupportedMethods))] public async Task ServerShouldReturnLastModified(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage response = await server.CreateClient().SendAsync( new HttpRequestMessage(method, "http://localhost/SubFolder/extra.xml")); @@ -179,7 +189,8 @@ public async Task ServerShouldReturnLastModified(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task MatchingBothConditionsReturnsNotModified(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server .CreateRequest("/SubFolder/extra.xml") .SendAsync(method.Method); @@ -198,7 +209,8 @@ public async Task MatchingBothConditionsReturnsNotModified(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task MatchingAtLeastOneETagReturnsNotModified(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server .CreateRequest("/SubFolder/extra.xml") .SendAsync(method.Method); @@ -223,7 +235,8 @@ public async Task MatchingAtLeastOneETagReturnsNotModified(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task MissingEitherOrBothConditionsReturnsNormally(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage resp1 = await server .CreateRequest("/SubFolder/extra.xml") .SendAsync(method.Method); @@ -271,7 +284,8 @@ public async Task MissingEitherOrBothConditionsReturnsNormally(HttpMethod method [MemberData(nameof(SupportedMethods))] public async Task InvalidIfModifiedSinceDateFormatGivesNormalGet(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res = await server .CreateRequest("/SubFolder/extra.xml") @@ -285,7 +299,8 @@ public async Task InvalidIfModifiedSinceDateFormatGivesNormalGet(HttpMethod meth [MemberData(nameof(SupportedMethods))] public async Task FutureIfModifiedSinceDateFormatGivesNormalGet(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res = await server .CreateRequest("/SubFolder/extra.xml") @@ -306,7 +321,8 @@ public async Task FutureIfModifiedSinceDateFormatGivesNormalGet(HttpMethod metho [MemberData(nameof(SupportedMethods))] public async Task IfModifiedSinceDateGreaterThanLastModifiedShouldReturn304(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res1 = await server .CreateRequest("/SubFolder/extra.xml") @@ -324,7 +340,8 @@ public async Task IfModifiedSinceDateGreaterThanLastModifiedShouldReturn304(Http [MemberData(nameof(SupportedMethods))] public async Task SupportsIfModifiedDateFormats(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res1 = await server .CreateRequest("/SubFolder/extra.xml") .SendAsync(method.Method); @@ -351,7 +368,8 @@ public async Task SupportsIfModifiedDateFormats(HttpMethod method) [MemberData(nameof(SupportedMethods))] public async Task IfModifiedSinceDateLessThanLastModifiedShouldReturn200(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res1 = await server .CreateRequest("/SubFolder/extra.xml") @@ -369,7 +387,8 @@ public async Task IfModifiedSinceDateLessThanLastModifiedShouldReturn200(HttpMet [MemberData(nameof(SupportedMethods))] public async Task InvalidIfUnmodifiedSinceDateFormatGivesNormalGet(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res = await server .CreateRequest("/SubFolder/extra.xml") @@ -383,7 +402,8 @@ public async Task InvalidIfUnmodifiedSinceDateFormatGivesNormalGet(HttpMethod me [MemberData(nameof(SupportedMethods))] public async Task FutureIfUnmodifiedSinceDateFormatGivesNormalGet(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res = await server .CreateRequest("/SubFolder/extra.xml") @@ -397,7 +417,8 @@ public async Task FutureIfUnmodifiedSinceDateFormatGivesNormalGet(HttpMethod met [MemberData(nameof(SupportedMethods))] public async Task IfUnmodifiedSinceDateLessThanLastModifiedShouldReturn412(HttpMethod method) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage res1 = await server .CreateRequest("/SubFolder/extra.xml") diff --git a/src/Middleware/StaticFiles/test/UnitTests/DefaultFilesMiddlewareTests.cs b/src/Middleware/StaticFiles/test/UnitTests/DefaultFilesMiddlewareTests.cs index 08e86714a4cb..16411ea59f5c 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/DefaultFilesMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/DefaultFilesMiddlewareTests.cs @@ -24,10 +24,12 @@ public class DefaultFilesMiddlewareTests public async Task NullArguments() { // No exception, default provided - StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions { FileProvider = null })); + using (await StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions { FileProvider = null }))) + { } // PathString(null) is OK. - var server = StaticFilesTestServer.Create(app => app.UseDefaultFiles((string)null)); + using var host = await StaticFilesTestServer.Create(app => app.UseDefaultFiles((string)null)); + using var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -64,7 +66,7 @@ private async Task NoMatch_PassesThrough(string baseUrl, string baseDir, string { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => + using var host = await StaticFilesTestServer.Create(app => { app.UseDefaultFiles(new DefaultFilesOptions { @@ -74,6 +76,7 @@ private async Task NoMatch_PassesThrough(string baseUrl, string baseDir, string }); app.Run(context => context.Response.WriteAsync(context.Request.Path.Value)); }); + using var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(requestUrl); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -86,7 +89,7 @@ public async Task Endpoint_PassesThrough() { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, "."))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => { app.UseRouting(); @@ -113,6 +116,7 @@ public async Task Endpoint_PassesThrough() app.UseEndpoints(endpoints => { }); }, services => { services.AddDirectoryBrowser(); services.AddRouting(); }); + using var server = host.GetTestServer(); var response = await server.CreateRequest("/SubFolder/").GetAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -165,7 +169,7 @@ private async Task FoundDirectoryWithDefaultFile_PathModified(string baseUrl, st { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => + using var host = await StaticFilesTestServer.Create(app => { app.UseDefaultFiles(new DefaultFilesOptions { @@ -175,6 +179,7 @@ private async Task FoundDirectoryWithDefaultFile_PathModified(string baseUrl, st }); app.Run(context => context.Response.WriteAsync(context.Request.Path.Value)); }); + using var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(requestUrl); @@ -211,11 +216,12 @@ private async Task NearMatch_RedirectAddSlash(string baseUrl, string baseDir, st { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions + using var host = await StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl + queryString).GetAsync(); Assert.Equal(HttpStatusCode.Moved, response.StatusCode); @@ -265,12 +271,13 @@ private async Task PostDirectory_PassesThrough(string baseUrl, string baseDir, s { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions + using var host = await StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider, RedirectToAppendTrailingSlash = appendTrailingSlash })); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).GetAsync(); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // Passed through diff --git a/src/Middleware/StaticFiles/test/UnitTests/DirectoryBrowserMiddlewareTests.cs b/src/Middleware/StaticFiles/test/UnitTests/DirectoryBrowserMiddlewareTests.cs index 5a39ec3ef9b0..e3cc2fa32dbf 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/DirectoryBrowserMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/DirectoryBrowserMiddlewareTests.cs @@ -21,10 +21,10 @@ namespace Microsoft.AspNetCore.StaticFiles public class DirectoryBrowserMiddlewareTests { [Fact] - public void WorksWithoutEncoderRegistered() + public async Task WorksWithoutEncoderRegistered() { // No exception, uses HtmlEncoder.Default - StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser()); } @@ -32,19 +32,24 @@ public void WorksWithoutEncoderRegistered() public async Task NullArguments() { // No exception, default provided - StaticFilesTestServer.Create( + using (await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { Formatter = null }), - services => services.AddDirectoryBrowser()); + services => services.AddDirectoryBrowser())) + { + } // No exception, default provided - StaticFilesTestServer.Create( + using (await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { FileProvider = null }), - services => services.AddDirectoryBrowser()); + services => services.AddDirectoryBrowser())) + { + } // PathString(null) is OK. - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser((string)null), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -82,7 +87,7 @@ private async Task NoMatch_PassesThrough(string baseUrl, string baseDir, string { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { RequestPath = new PathString(baseUrl), @@ -90,6 +95,7 @@ private async Task NoMatch_PassesThrough(string baseUrl, string baseDir, string RedirectToAppendTrailingSlash = appendTrailingSlash }), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).GetAsync(); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -100,7 +106,7 @@ public async Task Endpoint_PassesThrough() { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, "."))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => { app.UseRouting(); @@ -128,6 +134,7 @@ public async Task Endpoint_PassesThrough() app.UseEndpoints(endpoints => { }); }, services => { services.AddDirectoryBrowser(); services.AddRouting(); }); + using var server = host.GetTestServer(); var response = await server.CreateRequest("/").GetAsync(); Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); @@ -174,7 +181,7 @@ private async Task FoundDirectory_Served(string baseUrl, string baseDir, string { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { RequestPath = new PathString(baseUrl), @@ -182,6 +189,7 @@ private async Task FoundDirectory_Served(string baseUrl, string baseDir, string RedirectToAppendTrailingSlash = appendTrailingSlash, }), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).GetAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); @@ -217,13 +225,14 @@ private async Task NearMatch_RedirectAddSlash(string baseUrl, string baseDir, st { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider }), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl + queryString).GetAsync(); @@ -266,7 +275,7 @@ private async Task PostDirectory_PassesThrough(string baseUrl, string baseDir, s { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { RequestPath = new PathString(baseUrl), @@ -274,6 +283,7 @@ private async Task PostDirectory_PassesThrough(string baseUrl, string baseDir, s RedirectToAppendTrailingSlash = appendTrailingSlash }), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).PostAsync(); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); @@ -313,7 +323,7 @@ private async Task HeadDirectory_HeadersButNotBodyServed(string baseUrl, string { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create( + using var host = await StaticFilesTestServer.Create( app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { RequestPath = new PathString(baseUrl), @@ -321,6 +331,7 @@ private async Task HeadDirectory_HeadersButNotBodyServed(string baseUrl, string RedirectToAppendTrailingSlash = appendTrailingSlash }), services => services.AddDirectoryBrowser()); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).SendAsync("HEAD"); diff --git a/src/Middleware/StaticFiles/test/UnitTests/RangeHeaderTests.cs b/src/Middleware/StaticFiles/test/UnitTests/RangeHeaderTests.cs index 71e1d7274dce..2879616c8bbc 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/RangeHeaderTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/RangeHeaderTests.cs @@ -14,12 +14,13 @@ namespace Microsoft.AspNetCore.StaticFiles public class RangeHeaderTests { // 14.27 If-Range - // If the entity tag given in the If-Range header matches the current entity tag for the entity, then the server SHOULD + // If the entity tag given in the If-Range header matches the current entity tag for the entity, then the server SHOULD // provide the specified sub-range of the entity using a 206 (Partial content) response. [Fact] public async Task IfRangeWithCurrentEtagShouldServePartialContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -39,7 +40,8 @@ public async Task IfRangeWithCurrentEtagShouldServePartialContent() [Fact] public async Task HEADIfRangeWithCurrentEtagShouldReturn200Ok() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); @@ -59,7 +61,8 @@ public async Task HEADIfRangeWithCurrentEtagShouldReturn200Ok() [Fact] public async Task IfRangeWithCurrentDateShouldServePartialContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -75,7 +78,8 @@ public async Task IfRangeWithCurrentDateShouldServePartialContent() [Fact] public async Task IfModifiedSinceWithPastDateShouldServePartialContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -91,7 +95,8 @@ public async Task IfModifiedSinceWithPastDateShouldServePartialContent() [Fact] public async Task IfModifiedSinceWithCurrentDateShouldReturn304() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -107,7 +112,8 @@ public async Task IfModifiedSinceWithCurrentDateShouldReturn304() [Fact] public async Task HEADIfRangeWithCurrentDateShouldReturn200Ok() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); @@ -127,7 +133,8 @@ public async Task HEADIfRangeWithCurrentDateShouldReturn200Ok() [Fact] public async Task IfRangeWithOldEtagShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("If-Range", "\"OldEtag\""); req.Headers.Add("Range", "bytes=0-10"); @@ -143,7 +150,8 @@ public async Task IfRangeWithOldEtagShouldServeFullContent() [Fact] public async Task HEADIfRangeWithOldEtagShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("If-Range", "\"OldEtag\""); req.Headers.Add("Range", "bytes=0-10"); @@ -159,7 +167,8 @@ public async Task HEADIfRangeWithOldEtagShouldServeFullContent() [Fact] public async Task IfRangeWithOldDateShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -177,7 +186,8 @@ public async Task IfRangeWithOldDateShouldServeFullContent() [Fact] public async Task HEADIfRangeWithOldDateShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); @@ -191,12 +201,13 @@ public async Task HEADIfRangeWithOldDateShouldServeFullContent() } // 14.27 If-Range - // The If-Range header SHOULD only be used together with a Range header, and MUST be ignored if the request + // The If-Range header SHOULD only be used together with a Range header, and MUST be ignored if the request // does not include a Range header, or if the server does not support the sub-range operation. [Fact] public async Task IfRangeWithoutRangeShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); @@ -222,7 +233,8 @@ public async Task IfRangeWithoutRangeShouldServeFullContent() [Fact] public async Task HEADIfRangeWithoutRangeShouldServeFullContent() { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt"); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); @@ -256,7 +268,8 @@ public async Task HEADIfRangeWithoutRangeShouldServeFullContent() [InlineData("-1001", "0-61", 62, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")] public async Task SingleValidRangeShouldServePartialContent(string range, string expectedRange, int length, string expectedData) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -276,7 +289,8 @@ public async Task SingleValidRangeShouldServePartialContent(string range, string [InlineData("0-2", "0-0", 1, "A")] public async Task SingleValidRangeShouldServePartialContentSingleByteFile(string range, string expectedRange, int length, string expectedData) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/SingleByte.txt"); req.Headers.Add("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -296,7 +310,8 @@ public async Task SingleValidRangeShouldServePartialContentSingleByteFile(string [InlineData("0-2")] public async Task SingleValidRangeShouldServeRequestedRangeNotSatisfiableEmptyFile(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/Empty.txt"); req.Headers.Add("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -309,7 +324,8 @@ public async Task SingleValidRangeShouldServeRequestedRangeNotSatisfiableEmptyFi [InlineData("10-35")] public async Task HEADSingleValidRangeShouldReturnOk(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -326,7 +342,8 @@ public async Task HEADSingleValidRangeShouldReturnOk(string range) [InlineData("-0")] // Suffix range must be non-zero public async Task SingleNotSatisfiableRange(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); req.Headers.TryAddWithoutValidation("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -340,7 +357,8 @@ public async Task SingleNotSatisfiableRange(string range) [InlineData("1000-1001")] // Out of range public async Task HEADSingleNotSatisfiableRangeReturnsOk(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); req.Headers.TryAddWithoutValidation("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -359,7 +377,8 @@ public async Task HEADSingleNotSatisfiableRangeReturnsOk(string range) [InlineData("a-b")] public async Task SingleInvalidRangeIgnored(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); req.Headers.TryAddWithoutValidation("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -380,7 +399,8 @@ public async Task SingleInvalidRangeIgnored(string range) [InlineData("a-b")] public async Task HEADSingleInvalidRangeIgnored(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); req.Headers.TryAddWithoutValidation("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -400,7 +420,8 @@ public async Task HEADSingleInvalidRangeIgnored(string range) [InlineData("0-0,6-6,8-8,2-2,4-4")] public async Task MultipleValidRangesShouldServeFullContent(string ranges) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("Range", "bytes=" + ranges); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); @@ -419,7 +440,8 @@ public async Task MultipleValidRangesShouldServeFullContent(string ranges) [InlineData("2-2,0-0")] // SHOULD send in the requested order. public async Task HEADMultipleValidRangesShouldServeFullContent(string range) { - TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer()); + using var host = await StaticFilesTestServer.Create(app => app.UseFileServer()); + using var server = host.GetTestServer(); var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt"); req.Headers.Add("Range", "bytes=" + range); HttpResponseMessage resp = await server.CreateClient().SendAsync(req); diff --git a/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs b/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs index a91ac3efce0c..518927b50976 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/StaticFileMiddlewareTests.cs @@ -16,6 +16,7 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.FileProviders; +using Microsoft.Extensions.Hosting; using Moq; using Xunit; @@ -26,9 +27,17 @@ public class StaticFileMiddlewareTests [Fact] public async Task ReturnsNotFoundWithoutWwwroot() { - var builder = new WebHostBuilder() - .Configure(app => app.UseStaticFiles()); - var server = new TestServer(builder); + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .Configure(app => app.UseStaticFiles()); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/ranges.txt"); @@ -47,10 +56,18 @@ public async Task ReturnsNotFoundForBrokenSymlink() try { - var builder = new WebHostBuilder() + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() .Configure(app => app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true })) .UseWebRoot(AppContext.BaseDirectory); - var server = new TestServer(builder); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync(Path.GetFileName(badLink)); @@ -70,18 +87,26 @@ public async Task ReturnsNotFoundIfSendFileThrows() mockSendFile.Setup(m => m.SendFileAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ThrowsAsync(new FileNotFoundException()); mockSendFile.Setup(m => m.Stream).Returns(Stream.Null); - var builder = new WebHostBuilder() - .Configure(app => + using var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - app.Use(async (ctx, next) => + webHostBuilder + .UseTestServer() + .Configure(app => { - ctx.Features.Set(mockSendFile.Object); - await next(); - }); - app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true }); - }) - .UseWebRoot(AppContext.BaseDirectory); - var server = new TestServer(builder); + app.Use(async (ctx, next) => + { + ctx.Features.Set(mockSendFile.Object); + await next(); + }); + app.UseStaticFiles(new StaticFileOptions { ServeUnknownFileTypes = true }); + }) + .UseWebRoot(AppContext.BaseDirectory); + }).Build(); + + await host.StartAsync(); + + var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("TestDocument.txt"); @@ -94,10 +119,11 @@ public async Task FoundFile_LastModifiedTrimsSeconds() { using (var fileProvider = new PhysicalFileProvider(AppContext.BaseDirectory)) { - var server = StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions + using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { FileProvider = fileProvider })); + using var server = host.GetTestServer(); var fileInfo = fileProvider.GetFileInfo("TestDocument.txt"); var response = await server.CreateRequest("TestDocument.txt").GetAsync(); @@ -112,13 +138,16 @@ public async Task FoundFile_LastModifiedTrimsSeconds() public async Task NullArguments() { // No exception, default provided - StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = null })); + using (await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = null }))) + { } // No exception, default provided - StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { FileProvider = null })); + using (await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { FileProvider = null }))) + { } // PathString(null) is OK. - var server = StaticFilesTestServer.Create(app => app.UseStaticFiles((string)null)); + using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles((string)null)); + using var server = host.GetTestServer(); var response = await server.CreateClient().GetAsync("/"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } @@ -146,11 +175,12 @@ private async Task FoundFile_Served(string baseUrl, string baseDir, string reque { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions + using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); + using var server = host.GetTestServer(); var fileInfo = fileProvider.GetFileInfo(Path.GetFileName(requestUrl)); var response = await server.CreateRequest(requestUrl).GetAsync(); var responseContent = await response.Content.ReadAsByteArrayAsync(); @@ -176,11 +206,12 @@ public async Task HeadFile_HeadersButNotBodyServed(string baseUrl, string baseDi { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions + using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); + using var server = host.GetTestServer(); var fileInfo = fileProvider.GetFileInfo(Path.GetFileName(requestUrl)); var response = await server.CreateRequest(requestUrl).SendAsync("HEAD"); @@ -235,11 +266,12 @@ private async Task PassesThrough(string method, string baseUrl, string baseDir, { using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir))) { - var server = StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions + using var host = await StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString(baseUrl), FileProvider = fileProvider })); + using var server = host.GetTestServer(); var response = await server.CreateRequest(requestUrl).SendAsync(method); Assert.Null(response.Content.Headers.LastModified); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); diff --git a/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs b/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs index d4bdf06eed76..8f2723745097 100644 --- a/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs +++ b/src/Middleware/StaticFiles/test/UnitTests/StaticFilesTestServer.cs @@ -4,17 +4,19 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; +using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.StaticFiles { public static class StaticFilesTestServer { - public static TestServer Create(Action configureApp, Action configureServices = null) + public static async Task Create(Action configureApp, Action configureServices = null) { Action defaultConfigureServices = services => { }; var configuration = new ConfigurationBuilder() @@ -23,11 +25,18 @@ public static TestServer Create(Action configureApp, Action new KeyValuePair("webroot", ".") }) .Build(); - var builder = new WebHostBuilder() - .UseConfiguration(configuration) - .Configure(configureApp) - .ConfigureServices(configureServices ?? defaultConfigureServices); - return new TestServer(builder); + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseTestServer() + .UseConfiguration(configuration) + .Configure(configureApp) + .ConfigureServices(configureServices ?? defaultConfigureServices); + }).Build(); + + await host.StartAsync(); + return host; } } -} \ No newline at end of file +} diff --git a/src/Middleware/WebSockets/samples/EchoApp/Program.cs b/src/Middleware/WebSockets/samples/EchoApp/Program.cs index 07dd98e134be..0723252c76e7 100644 --- a/src/Middleware/WebSockets/samples/EchoApp/Program.cs +++ b/src/Middleware/WebSockets/samples/EchoApp/Program.cs @@ -1,24 +1,26 @@ -using System; -using System.Collections.Generic; using System.IO; -using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; namespace EchoApp { public class Program { - public static void Main(string[] args) + public static Task Main(string[] args) { - var host = new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseStartup() + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => + { + webHostBuilder + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup(); + }) .Build(); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Program.cs b/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Program.cs index ddd340a6e003..c65ab23ac2dc 100644 --- a/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Program.cs +++ b/src/Middleware/WebSockets/test/ConformanceTests/AutobahnTestApp/Program.cs @@ -1,76 +1,81 @@ using System; using System.IO; using System.Net; -using System.Runtime.Loader; +using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace AutobahnTestApp { public class Program { - public static void Main(string[] args) + public static Task Main(string[] args) { var scenarioName = "Unknown"; var config = new ConfigurationBuilder() .AddCommandLine(args) .Build(); - var builder = new WebHostBuilder() - .ConfigureLogging(loggingBuilder => loggingBuilder.AddConsole()) - .UseConfiguration(config) - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseStartup(); - - if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal)) - { - scenarioName = "HttpSysServer"; - Console.WriteLine("Using HttpSys server"); - builder.UseHttpSys(); - } - else if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT"))) - { - // ANCM is hosting the process. - // The port will not yet be configured at this point, but will also not require HTTPS. - scenarioName = "AspNetCoreModule"; - Console.WriteLine("Detected ANCM, using Kestrel"); - builder.UseKestrel(); - } - else - { - // Also check "server.urls" for back-compat. - var urls = builder.GetSetting(WebHostDefaults.ServerUrlsKey) ?? builder.GetSetting("server.urls"); - builder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Empty); - - Console.WriteLine($"Using Kestrel, URL: {urls}"); - - if (urls.Contains(";")) + var builder = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - throw new NotSupportedException("This test app does not support multiple endpoints."); - } + webHostBuilder + .ConfigureLogging(loggingBuilder => loggingBuilder.AddConsole()) + .UseConfiguration(config) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseStartup(); - var uri = new Uri(urls); - - builder.UseKestrel(options => - { - options.Listen(IPAddress.Loopback, uri.Port, listenOptions => + if (string.Equals(webHostBuilder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal)) { - if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) + scenarioName = "HttpSysServer"; + Console.WriteLine("Using HttpSys server"); + webHostBuilder.UseHttpSys(); + } + else if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_PORT"))) + { + // ANCM is hosting the process. + // The port will not yet be configured at this point, but will also not require HTTPS. + scenarioName = "AspNetCoreModule"; + Console.WriteLine("Detected ANCM, using Kestrel"); + webHostBuilder.UseKestrel(); + } + else + { + // Also check "server.urls" for back-compat. + var urls = webHostBuilder.GetSetting(WebHostDefaults.ServerUrlsKey) ?? webHostBuilder.GetSetting("server.urls"); + webHostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Empty); + + Console.WriteLine($"Using Kestrel, URL: {urls}"); + + if (urls.Contains(";")) { - scenarioName = "Kestrel(SSL)"; - var certPath = Path.Combine(AppContext.BaseDirectory, "TestResources", "testCert.pfx"); - Console.WriteLine($"Using SSL with certificate: {certPath}"); - listenOptions.UseHttps(certPath, "testPassword"); + throw new NotSupportedException("This test app does not support multiple endpoints."); } - else + + var uri = new Uri(urls); + + webHostBuilder.UseKestrel(options => { - scenarioName = "Kestrel(NonSSL)"; - } - }); + options.Listen(IPAddress.Loopback, uri.Port, listenOptions => + { + if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) + { + scenarioName = "Kestrel(SSL)"; + var certPath = Path.Combine(AppContext.BaseDirectory, "TestResources", "testCert.pfx"); + Console.WriteLine($"Using SSL with certificate: {certPath}"); + listenOptions.UseHttps(certPath, "testPassword"); + } + else + { + scenarioName = "Kestrel(NonSSL)"; + } + }); + }); + } }); - } var host = builder.Build(); @@ -80,7 +85,7 @@ public static void Main(string[] args) }; Console.WriteLine($"Starting Server for Scenario: {scenarioName}"); - host.Run(); + return host.RunAsync(); } } } diff --git a/src/Middleware/WebSockets/test/UnitTests/IHostPortExtensions.cs b/src/Middleware/WebSockets/test/UnitTests/IHostPortExtensions.cs new file mode 100644 index 000000000000..3cea6f8e92f4 --- /dev/null +++ b/src/Middleware/WebSockets/test/UnitTests/IHostPortExtensions.cs @@ -0,0 +1,33 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace Microsoft.AspNetCore.Hosting +{ + public static class IHostPortExtensions + { + public static int GetPort(this IHost host) + { + return host.GetPorts().First(); + } + + public static IEnumerable GetPorts(this IHost host) + { + return host.GetUris() + .Select(u => u.Port); + } + + public static IEnumerable GetUris(this IHost host) + { + return host.Services.GetService().Features.Get().Addresses + .Select(a => new Uri(a)); + } + } +} diff --git a/src/Middleware/WebSockets/test/UnitTests/IWebHostPortExtensions.cs b/src/Middleware/WebSockets/test/UnitTests/IWebHostPortExtensions.cs deleted file mode 100644 index d3b53681f40b..000000000000 --- a/src/Middleware/WebSockets/test/UnitTests/IWebHostPortExtensions.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Hosting.Server.Features; - -namespace Microsoft.AspNetCore.Hosting -{ - public static class IWebHostPortExtensions - { - public static int GetPort(this IWebHost host) - { - return host.GetPorts().First(); - } - - public static IEnumerable GetPorts(this IWebHost host) - { - return host.GetUris() - .Select(u => u.Port); - } - - public static IEnumerable GetUris(this IWebHost host) - { - return host.ServerFeatures.Get().Addresses - .Select(a => new Uri(a)); - } - } -} \ No newline at end of file diff --git a/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs b/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs index 8f24cb92e7dd..1d591e8e43b6 100644 --- a/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs +++ b/src/Middleware/WebSockets/test/UnitTests/KestrelWebSocketHelpers.cs @@ -9,6 +9,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.WebSockets.Test { @@ -48,16 +49,19 @@ public static IDisposable CreateServer(ILoggerFactory loggerFactory, out int por var config = configBuilder.Build(); config["server.urls"] = $"http://127.0.0.1:0"; - var host = new WebHostBuilder() - .ConfigureServices(s => + var host = new HostBuilder() + .ConfigureWebHost(webHostBuilder => { - s.AddWebSockets(configure); - s.AddSingleton(loggerFactory); - }) - .UseConfiguration(config) - .UseKestrel() - .Configure(startup) - .Build(); + webHostBuilder + .ConfigureServices(s => + { + s.AddWebSockets(configure); + s.AddSingleton(loggerFactory); + }) + .UseConfiguration(config) + .UseKestrel() + .Configure(startup); + }).Build(); host.Start(); port = host.GetPort();