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?
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