简体   繁体   English

为什么 TestServer (AspNetCore) 在静态文件上给出 404 错误?

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

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):我正在使用 xunit 测试(学习):

        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).一切正常(200)。 Now I am changing Startup.cs现在我正在更改 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).如果我用浏览器启动应用程序,一切正常(显示 index.html)。 But if I call it with the TestServer I receive (404 Not found).但是如果我用 TestServer 调用它,我会收到(404 Not found)。 Where is my error?我的错误在哪里?

Another approach is to copy those files into your unit test project另一种方法是将这些文件复制到您的单元测试项目中

在此处输入图片说明

Then然后

在此处输入图片说明

As far as you maintain the same structure folder of the project that you are testing, it will find out the files and pass it to the dependency injection process.只要您维护与您正在测试的项目相同的结构文件夹,它就会找出文件并将其传递给依赖注入过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM