Example #1
0
        public async Task SingleInvalidRangeIgnored(string range)
        {
            TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer());
            var        req    = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt");

            req.Headers.TryAddWithoutValidation("Range", "bytes=" + range);
            HttpResponseMessage resp = await server.CreateClient().SendAsync(req);

            Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
            Assert.Null(resp.Content.Headers.ContentRange);
            Assert.Equal(62, resp.Content.Headers.ContentLength);
            Assert.Equal("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", await resp.Content.ReadAsStringAsync());
        }
Example #2
0
        public async Task HEADSingleInvalidRangeIgnored(string range)
        {
            TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer());
            var        req    = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt");

            req.Headers.TryAddWithoutValidation("Range", "bytes=" + range);
            HttpResponseMessage resp = await server.CreateClient().SendAsync(req);

            Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
            Assert.Null(resp.Content.Headers.ContentRange);
            Assert.Equal(62, resp.Content.Headers.ContentLength);
            Assert.Equal(string.Empty, await resp.Content.ReadAsStringAsync());
        }
Example #3
0
        public async Task IfModifiedSinceWithCurrentDateShouldReturn304()
        {
            TestServer          server   = StaticFilesTestServer.Create(app => app.UseFileServer());
            HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt");

            var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt");

            req.Headers.Add("If-Modified-Since", original.Content.Headers.LastModified.Value.ToString("r"));
            req.Headers.Add("Range", "bytes=0-10");
            HttpResponseMessage resp = await server.CreateClient().SendAsync(req);

            Assert.Equal(HttpStatusCode.NotModified, resp.StatusCode);
        }
Example #4
0
        public async Task HEADIfRangeWithOldEtagShouldServeFullContent()
        {
            TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer());
            var        req    = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt");

            req.Headers.Add("If-Range", "\"OldEtag\"");
            req.Headers.Add("Range", "bytes=0-10");
            HttpResponseMessage resp = await server.CreateClient().SendAsync(req);

            Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
            Assert.Null(resp.Content.Headers.ContentRange);
            Assert.Equal(62, resp.Content.Headers.ContentLength);
            Assert.Equal(string.Empty, await resp.Content.ReadAsStringAsync());
        }
Example #5
0
        public async Task IfRangeWithOldEtagShouldServeFullContent()
        {
            TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer());
            var        req    = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt");

            req.Headers.Add("If-Range", "\"OldEtag\"");
            req.Headers.Add("Range", "bytes=0-10");
            HttpResponseMessage resp = await server.CreateClient().SendAsync(req);

            Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
            Assert.Null(resp.Content.Headers.ContentRange);
            Assert.Equal(62, resp.Content.Headers.ContentLength);
            Assert.Equal("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", await resp.Content.ReadAsStringAsync());
        }
Example #6
0
        private async Task PostDirectory_PassesThrough(string baseUrl, string baseDir, string requestUrl)
        {
            using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir)))
            {
                var server = StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions
                {
                    RequestPath  = new PathString(baseUrl),
                    FileProvider = fileProvider
                }));
                var response = await server.CreateRequest(requestUrl).GetAsync();

                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); // Passed through
            }
        }
Example #7
0
        public async Task SingleValidRangeShouldServePartialContentSingleByteFile(string range, string expectedRange, int length, string expectedData)
        {
            TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer());
            var        req    = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/SingleByte.txt");

            req.Headers.Add("Range", "bytes=" + range);
            HttpResponseMessage resp = await server.CreateClient().SendAsync(req);

            Assert.Equal(HttpStatusCode.PartialContent, resp.StatusCode);
            Assert.NotNull(resp.Content.Headers.ContentRange);
            Assert.Equal("bytes " + expectedRange + "/1", resp.Content.Headers.ContentRange.ToString());
            Assert.Equal(length, resp.Content.Headers.ContentLength);
            Assert.Equal(expectedData, await resp.Content.ReadAsStringAsync());
        }
 private async Task NoMatch_PassesThrough(string baseUrl, string baseDir, string requestUrl)
 {
     using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir)))
     {
         var server = StaticFilesTestServer.Create(
             app => app.UseDirectoryBrowser(new DirectoryBrowserOptions
             {
                 RequestPath = new PathString(baseUrl),
                 FileProvider = fileProvider
             }),
             services => services.AddDirectoryBrowser());
         var response = await server.CreateRequest(requestUrl).GetAsync();
         Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
     }
 }
Example #9
0
        public async Task IfUnmodifiedSinceDateLessThanLastModifiedShouldReturn412(HttpMethod method)
        {
            TestServer server = StaticFilesTestServer.Create(app => app.UseFileServer());

            HttpResponseMessage res1 = await server
                                       .CreateRequest("/SubFolder/extra.xml")
                                       .SendAsync(method.Method);

            HttpResponseMessage res2 = await server
                                       .CreateRequest("/SubFolder/extra.xml")
                                       .And(req => req.Headers.IfUnmodifiedSince = DateTimeOffset.MinValue)
                                       .SendAsync(method.Method);

            Assert.Equal(HttpStatusCode.PreconditionFailed, res2.StatusCode);
        }
Example #10
0
        private async Task PassesThrough(string method, string baseUrl, string baseDir, string requestUrl)
        {
            using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir)))
            {
                var server = StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions
                {
                    RequestPath  = new PathString(baseUrl),
                    FileProvider = fileProvider
                }));
                var response = await server.CreateRequest(requestUrl).SendAsync(method);

                Assert.Null(response.Content.Headers.LastModified);
                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            }
        }
Example #11
0
        public async Task MatchingBothConditionsReturnsNotModified(HttpMethod method)
        {
            TestServer          server = StaticFilesTestServer.Create(app => app.UseFileServer());
            HttpResponseMessage resp1  = await server
                                         .CreateRequest("/SubFolder/extra.xml")
                                         .SendAsync(method.Method);

            HttpResponseMessage resp2 = await server
                                        .CreateRequest("/SubFolder/extra.xml")
                                        .AddHeader("If-None-Match", resp1.Headers.ETag.ToString())
                                        .And(req => req.Headers.IfModifiedSince = resp1.Content.Headers.LastModified)
                                        .SendAsync(method.Method);

            Assert.Equal(HttpStatusCode.NotModified, resp2.StatusCode);
        }
Example #12
0
        public async Task IfModifiedSinceWithPastDateShouldServePartialContent()
        {
            TestServer          server   = StaticFilesTestServer.Create(app => app.UseFileServer());
            HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt");

            var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost/SubFolder/ranges.txt");

            req.Headers.Add("If-Modified-Since", original.Content.Headers.LastModified.Value.AddHours(-1).ToString("r"));
            req.Headers.Add("Range", "bytes=0-10");
            HttpResponseMessage resp = await server.CreateClient().SendAsync(req);

            Assert.Equal(HttpStatusCode.PartialContent, resp.StatusCode);
            Assert.Equal("bytes 0-10/62", resp.Content.Headers.ContentRange.ToString());
            Assert.Equal(11, resp.Content.Headers.ContentLength);
            Assert.Equal("0123456789a", await resp.Content.ReadAsStringAsync());
        }
Example #13
0
        public async Task HEADIfRangeWithOldDateShouldServeFullContent()
        {
            TestServer          server   = StaticFilesTestServer.Create(app => app.UseFileServer());
            HttpResponseMessage original = await server.CreateClient().GetAsync("http://localhost/SubFolder/ranges.txt");

            var req = new HttpRequestMessage(HttpMethod.Head, "http://localhost/SubFolder/ranges.txt");

            req.Headers.Add("If-Range", original.Content.Headers.LastModified.Value.Subtract(TimeSpan.FromDays(1)).ToString("r"));
            req.Headers.Add("Range", "bytes=0-10");
            HttpResponseMessage resp = await server.CreateClient().SendAsync(req);

            Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
            Assert.Null(resp.Content.Headers.ContentRange);
            Assert.Equal(62, resp.Content.Headers.ContentLength);
            Assert.Equal(string.Empty, await resp.Content.ReadAsStringAsync());
        }
Example #14
0
        public async Task FoundFile_LastModifiedTrimsSeconds()
        {
            using (var fileProvider = new PhysicalFileProvider(AppContext.BaseDirectory))
            {
                var server = StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider = fileProvider
                }));
                var fileInfo = fileProvider.GetFileInfo("TestDocument.txt");
                var response = await server.CreateRequest("TestDocument.txt").GetAsync();

                var last    = fileInfo.LastModified;
                var trimmed = new DateTimeOffset(last.Year, last.Month, last.Day, last.Hour, last.Minute, last.Second, last.Offset).ToUniversalTime();

                Assert.Equal(response.Content.Headers.LastModified.Value, trimmed);
            }
        }
Example #15
0
        public async Task HeadFile_HeadersButNotBodyServed(string baseUrl, string baseDir, string requestUrl)
        {
            using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir)))
            {
                var server = StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions
                {
                    RequestPath  = new PathString(baseUrl),
                    FileProvider = fileProvider
                }));
                var fileInfo = fileProvider.GetFileInfo(Path.GetFileName(requestUrl));
                var response = await server.CreateRequest(requestUrl).SendAsync("HEAD");

                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()));
            }
        }
Example #16
0
        public async Task NullArguments()
        {
            // No exception, default provided
            StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions {
                ContentTypeProvider = null
            }));

            // No exception, default provided
            StaticFilesTestServer.Create(app => app.UseStaticFiles(new StaticFileOptions {
                FileProvider = null
            }));

            // PathString(null) is OK.
            var server   = StaticFilesTestServer.Create(app => app.UseStaticFiles((string)null));
            var response = await server.CreateClient().GetAsync("/");

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
        private async Task FoundDirectory_Served(string baseUrl, string baseDir, string requestUrl)
        {
            using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir)))
            {
                var server = StaticFilesTestServer.Create(
                    app => app.UseDirectoryBrowser(new DirectoryBrowserOptions
                    {
                        RequestPath = new PathString(baseUrl),
                        FileProvider = fileProvider
                    }),
                    services => services.AddDirectoryBrowser());
                var response = await server.CreateRequest(requestUrl).GetAsync();

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType.ToString());
                Assert.True(response.Content.Headers.ContentLength > 0);
                Assert.Equal(response.Content.Headers.ContentLength, (await response.Content.ReadAsByteArrayAsync()).Length);
            }
        }
Example #18
0
        private async Task NearMatch_RedirectAddSlash(string baseUrl, string baseDir, string requestUrl, string queryString)
        {
            using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir)))
            {
                var server = StaticFilesTestServer.Create(app => app.UseDefaultFiles(new DefaultFilesOptions
                {
                    RequestPath  = new PathString(baseUrl),
                    FileProvider = fileProvider
                }));
                var response = await server.CreateRequest(requestUrl + queryString).GetAsync();

                Assert.Equal(HttpStatusCode.Moved, response.StatusCode);
                // the url in the header of `Location: /xxx/xxx` should be encoded
                var expectedURL = UriHelper.BuildRelative(baseUrl, requestUrl + "/", new QueryString(queryString), new FragmentString());
                var actualURL   = response.Headers.GetValues("Location").FirstOrDefault();
                Assert.Equal(expectedURL, actualURL);
                Assert.Empty((await response.Content.ReadAsByteArrayAsync()));
            }
        }
        private async Task NearMatch_RedirectAddSlash(string baseUrl, string baseDir, string requestUrl, string queryString)
        {
            using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir)))
            {
                var server = StaticFilesTestServer.Create(
                    app => app.UseDirectoryBrowser(new DirectoryBrowserOptions
                    {
                        RequestPath = new PathString(baseUrl),
                        FileProvider = fileProvider
                    }),
                    services => services.AddDirectoryBrowser());

                var response = await server.CreateRequest(requestUrl + queryString).GetAsync();

                Assert.Equal(HttpStatusCode.Moved, response.StatusCode);
                Assert.Equal(requestUrl + "/" + queryString, response.Headers.GetValues("Location").FirstOrDefault());
                Assert.Empty((await response.Content.ReadAsByteArrayAsync()));
            }
        }
        public async Task NullArguments()
        {
            // No exception, default provided
            StaticFilesTestServer.Create(
                app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { Formatter = null }),
            services => services.AddDirectoryBrowser());

            // No exception, default provided
            StaticFilesTestServer.Create(
                app => app.UseDirectoryBrowser(new DirectoryBrowserOptions { FileProvider = null }),
                services => services.AddDirectoryBrowser());

            // PathString(null) is OK.
            var server = StaticFilesTestServer.Create(
                app => app.UseDirectoryBrowser((string)null),
                services => services.AddDirectoryBrowser());

            var response = await server.CreateClient().GetAsync("/");
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
Example #21
0
        private async Task NoMatch_PassesThrough(string baseUrl, string baseDir, string requestUrl)
        {
            using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, baseDir)))
            {
                var server = StaticFilesTestServer.Create(app =>
                {
                    app.UseDefaultFiles(new DefaultFilesOptions
                    {
                        RequestPath  = new PathString(baseUrl),
                        FileProvider = fileProvider
                    });
                    app.Run(context => context.Response.WriteAsync(context.Request.Path.Value));
                });

                var response = await server.CreateClient().GetAsync(requestUrl);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                Assert.Equal(requestUrl, await response.Content.ReadAsStringAsync()); // Should not be modified
            }
        }
Example #22
0
        public async Task Endpoint_PassesThrough()
        {
            using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, ".")))
            {
                var server = StaticFilesTestServer.Create(
                    app =>
                {
                    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(context.Request.Path.Value));
                        },
                                                         new EndpointMetadataCollection(),
                                                         "test"));

                        return(next(context));
                    });

                    app.UseDefaultFiles(new DefaultFilesOptions
                    {
                        RequestPath  = new PathString(""),
                        FileProvider = fileProvider
                    });

                    app.UseEndpoints(endpoints => {});
                },
                    services => { services.AddDirectoryBrowser(); services.AddRouting(); });

                var response = await server.CreateRequest("/SubFolder/").GetAsync();

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                Assert.Equal("/SubFolder/", await response.Content.ReadAsStringAsync()); // Should not be modified
            }
        }
        public async Task Endpoint_PassesThrough()
        {
            using (var fileProvider = new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, ".")))
            {
                var server = StaticFilesTestServer.Create(
                    app =>
                    {
                        app.UseRouting();

                        app.Use(next => context =>
                        {
                            // Assign an endpoint, this will make the directory browser noop
                            context.SetEndpoint(new Endpoint((c) =>
                            {
                                c.Response.StatusCode = (int)HttpStatusCode.NotAcceptable;
                                return c.Response.WriteAsync("Hi from endpoint.");
                            },
                            new EndpointMetadataCollection(),
                            "test"));

                            return next(context);
                        });

                        app.UseDirectoryBrowser(new DirectoryBrowserOptions
                        {
                            RequestPath = new PathString(""),
                            FileProvider = fileProvider
                        });

                        app.UseEndpoints(endpoints => {});
                    },
                    services => { services.AddDirectoryBrowser(); services.AddRouting(); });

                var response = await server.CreateRequest("/").GetAsync();
                Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
                Assert.Equal("Hi from endpoint.", await response.Content.ReadAsStringAsync());
            }
        }
Example #24
0
        public async Task MatchingAtLeastOneETagReturnsNotModified(HttpMethod method)
        {
            TestServer          server = StaticFilesTestServer.Create(app => app.UseFileServer());
            HttpResponseMessage resp1  = await server
                                         .CreateRequest("/SubFolder/extra.xml")
                                         .SendAsync(method.Method);

            var etag = resp1.Headers.ETag.ToString();

            HttpResponseMessage resp2 = await server
                                        .CreateRequest("/SubFolder/extra.xml")
                                        .AddHeader("If-Match", etag + ", " + etag)
                                        .SendAsync(method.Method);

            Assert.Equal(HttpStatusCode.OK, resp2.StatusCode);

            HttpResponseMessage resp3 = await server
                                        .CreateRequest("/SubFolder/extra.xml")
                                        .AddHeader("If-Match", etag + ", \"badetag\"")
                                        .SendAsync(method.Method);

            Assert.Equal(HttpStatusCode.OK, resp3.StatusCode);
        }
Example #25
0
        public async Task SupportsIfModifiedDateFormats(HttpMethod method)
        {
            TestServer          server = StaticFilesTestServer.Create(app => app.UseFileServer());
            HttpResponseMessage res1   = await server
                                         .CreateRequest("/SubFolder/extra.xml")
                                         .SendAsync(method.Method);

            var formats = new[]
            {
                "ddd, dd MMM yyyy HH:mm:ss 'GMT'",
                "dddd, dd-MMM-yy HH:mm:ss 'GMT'",
                "ddd MMM  d HH:mm:ss yyyy"
            };

            foreach (var format in formats)
            {
                HttpResponseMessage res2 = await server
                                           .CreateRequest("/SubFolder/extra.xml")
                                           .AddHeader("If-Modified-Since", DateTimeOffset.UtcNow.ToString(format))
                                           .SendAsync(method.Method);

                Assert.Equal(HttpStatusCode.NotModified, res2.StatusCode);
            }
        }
 public void WorksWithoutEncoderRegistered()
 {
     // No exception, uses HtmlEncoder.Default
     StaticFilesTestServer.Create(
         app => app.UseDirectoryBrowser());
 }