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 { RequestPath = new PathString(baseUrl), })); using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) { var hostingEnvironment = server.Services.GetService <IWebHostEnvironment>(); using (var client = new HttpClient { BaseAddress = new Uri(server.GetAddress()) }) { 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())); } } }
public async Task FoundFile_LastModifiedTrimsSeconds() { 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 client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { 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(); Assert.Equal(response.Content.Headers.LastModified.Value, trimmed); } }
private async Task ClientDisconnect_NoWriteExceptionThrown(ServerType serverType) { var interval = TimeSpan.FromSeconds(15); var requestReceived = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously); var requestCancelled = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously); var responseComplete = new TaskCompletionSource <int>(TaskCreationOptions.RunContinuationsAsynchronously); Exception exception = null; using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .ConfigureServices(services => services.AddSingleton(LoggerFactory)) .UseWebRoot(Path.Combine(AppContext.BaseDirectory)) .Configure(app => { app.Use(async(context, next) => { 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(); await host.StartAsync(); // 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); await responseComplete.Task.TimeoutAfter(interval); Assert.Null(exception); }
public async Task ReturnsFileForDefaultPattern() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .ConfigureServices(services => { services.AddRouting(); services.AddSingleton(LoggerFactory); }) .UseKestrel() .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) .UseWebRoot(AppContext.BaseDirectory) .Configure(app => { var environment = app.ApplicationServices.GetRequiredService <IWebHostEnvironment>(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.Map("/hello", context => { return(context.Response.WriteAsync("Hello, world!")); }); endpoints.MapFallbackToFile("default.html", new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(environment.WebRootPath, "SubFolder")), }); }); }); }).Build(); await host.StartAsync(); var environment = host.Services.GetRequiredService <IWebHostEnvironment>(); using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { var response = await client.GetAsync("hello"); var responseText = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Hello, world!", responseText); response = await client.GetAsync("/"); var responseContent = await response.Content.ReadAsByteArrayAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); AssertFileEquals(environment, "SubFolder/default.html", responseContent); } }
private void ClientDisconnect_NoWriteExceptionThrown(ServerType serverType) { var interval = TimeSpan.FromSeconds(15); var requestReceived = new ManualResetEvent(false); var requestCancelled = new ManualResetEvent(false); var responseComplete = new ManualResetEvent(false); Exception exception = null; var builder = new WebHostBuilder() .ConfigureServices(services => services.AddSingleton(LoggerFactory)) .UseWebRoot(Path.Combine(AppContext.BaseDirectory)) .Configure(app => { app.Use(async(context, next) => { try { requestReceived.Set(); Assert.True(requestCancelled.WaitOne(interval), "not cancelled"); Assert.True(context.RequestAborted.WaitHandle.WaitOne(interval), "not aborted"); await next(); } catch (Exception ex) { exception = ex; } responseComplete.Set(); }); app.UseStaticFiles(); }); if (serverType == ServerType.HttpSys) { builder.UseHttpSys(); } else if (serverType == ServerType.Kestrel) { builder.UseKestrel(); } using (var server = builder.Start(TestUrlHelper.GetTestUrl(serverType))) { // We don't use HttpClient here because it's disconnect behavior varies across platforms. var socket = SendSocketRequestAsync(server.GetAddress(), "/TestDocument1MB.txt"); Assert.True(requestReceived.WaitOne(interval), "not received"); socket.LingerState = new LingerOption(true, 0); socket.Dispose(); requestCancelled.Set(); Assert.True(responseComplete.WaitOne(interval), "not completed"); Assert.Null(exception); } }
public async Task ReturnsFileForCustomPattern() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .ConfigureServices(services => { services.AddRouting(); services.AddSingleton(LoggerFactory); }) .UseKestrel() .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) .UseWebRoot(AppContext.BaseDirectory) .Configure(app => { app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.Map("/hello", context => { return(context.Response.WriteAsync("Hello, world!")); }); endpoints.MapFallbackToFile("/prefix/{*path:nonfile}", "TestDocument.txt"); }); }); }).Build(); await host.StartAsync(); var environment = host.Services.GetRequiredService <IWebHostEnvironment>(); using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { var response = await client.GetAsync("hello"); var responseText = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Hello, world!", responseText); response = await client.GetAsync("prefix/Some-Path"); var responseContent = await response.Content.ReadAsByteArrayAsync(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); AssertFileEquals(environment, "TestDocument.txt", responseContent); } }
public async Task Endpoint_PassesThrough() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .ConfigureServices(services => { services.AddSingleton(LoggerFactory); services.AddRouting(); }) .UseKestrel() .UseUrls(TestUrlHelper.GetTestUrl(ServerType.Kestrel)) .UseWebRoot(AppContext.BaseDirectory) .Configure(app => { // Routing first => static files noops app.UseRouting(); app.Use(next => context => { // 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)); }); app.UseStaticFiles(); app.UseEndpoints(endpoints => { }); }); }).Build(); await host.StartAsync(); using (var client = new HttpClient { BaseAddress = new Uri(Helpers.GetAddress(host)) }) { var response = await client.GetAsync("TestDocument.txt"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Hi from endpoint.", await response.Content.ReadAsStringAsync()); } }
public async Task ReturnsNotFoundWithoutWwwroot() { var builder = new WebHostBuilder() .ConfigureServices(services => services.AddSingleton(LoggerFactory)) .UseKestrel() .Configure(app => app.UseStaticFiles()); using (var server = builder.Start(TestUrlHelper.GetTestUrl(ServerType.Kestrel))) { using (var client = new HttpClient { BaseAddress = new Uri(server.GetAddress()) }) { var response = await client.GetAsync("TestDocument.txt"); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } } }
private async Task FoundFile_Served(string baseUrl, string baseDir, string requestUrl) { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { 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(); await host.StartAsync(); var hostingEnvironment = host.Services.GetService <IWebHostEnvironment>(); 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(); 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)); } } }
public void GenerateUrl_FastAndSlowPathsReturnsExpected( string appBase, string protocol, string host, string virtualPath, string fragment, string expected) { // Arrange var services = CreateServices(); var httpContext = CreateHttpContext(services, appBase, host, protocol); var actionContext = CreateActionContext(httpContext); var urlHelper = new TestUrlHelper(actionContext); // Act var url = urlHelper.GenerateUrl(protocol, host, virtualPath, fragment); // Assert Assert.Equal(expected, url); }