为什么TestServer(AspNetCore)在静态文件上显示404错误? [英] Why the TestServer (AspNetCore) gives 404 error on static files?

查看:407
本文介绍了为什么TestServer(AspNetCore)在静态文件上显示404错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例服务器

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

            host.Run();

在Startup类中进行配置:

with configuration in Startup class:

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

我正在使用xunit测试(学习):

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);
        }

及更高版本

        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);

一切都很好(200)。现在我要更改Startup.cs

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!");
        //});
    }

如果我使用浏览器启动应用,一切正常(显示index.html )。但是,如果我用TestServer调用它,则会收到(404未找到)。我的错误在哪里?

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?

推荐答案

XUnit从另一个目录启动站点。我们必须像这样解决它: https://github.com/aspnet/StaticFiles/blob/d692066b2bd711653150ad2cccc2268583355532/test/Microsoft.AspNetCore.StaticFiles.Tests/StaticFilesTestServer.cs#L20

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

这篇关于为什么TestServer(AspNetCore)在静态文件上显示404错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆