Why the TestServer (AspNetCore) gives 404 error on static files?

二次信任 提交于 2019-12-01 11:36:37

问题


I have a sample server

var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();

with configuration in Startup class:

public void Configure(IApplicationBuilder app)
{
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
}

and I am using xunit test (learning):

        public TestFixture()
        {
            var builder = new WebHostBuilder().UseStartup<TStartup>();
            _server = new TestServer(builder);

            Client = _server.CreateClient();
            Client.BaseAddress = new Uri(address);
        }

and later

        var response = await Client.GetAsync("http://localhost:51021/");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        var responseString = await response.Content.ReadAsStringAsync();
        var content = await response.Content.ReadAsStringAsync();
        Assert.Contains("Hello World!", content);

Everything is OK (200). Now I am changing Startup.cs

    public void Configure(IApplicationBuilder app)
    {
        app.UseDefaultFiles();
        app.UseStaticFiles();
        //app.Run(async (context) =>
        //{
        //    await context.Response.WriteAsync("Hello World!");
        //});
    }

If I start the app with browser, everything is OK (index.html shown). But if I call it with the TestServer I receive (404 Not found). Where is my error?


回答1:


XUnit starts the site from a different directory. We've had to work around it like this: https://github.com/aspnet/StaticFiles/blob/d692066b2bd711653150ad2cccc2268583355532/test/Microsoft.AspNetCore.StaticFiles.Tests/StaticFilesTestServer.cs#L20



来源:https://stackoverflow.com/questions/37815267/why-the-testserver-aspnetcore-gives-404-error-on-static-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!