PhysicalFileProvider 应该如何在 asp.net 控制器中工作

How is PhysicalFileProvider supposed to work in asp.net controllers

请考虑以下(部分)IApplicationBuilder 和 IWebHostEnvironment 配置:

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "WebContent")),
    RequestPath = "/WebContent"
});

在我的控制器中,我正在测试 3 种不同的方法:

return LocalRedirect("~/WebContent/index.html");

这行得通,但我正在努力解决接下来的两个问题,想知道它们为什么会失败:

return PhysicalFile("~/WebContent/index.html", "text/html");

抛出:FileNotFoundException:找不到文件 'C:\ProjectPath>\bin\Debug\net5.0~\WebContent\index.html'。

return File("~/WebContent/index.html", "text/html");

抛出:FileNotFoundException:找不到文件:~/WebContent/index.html

我如何access/serve 后两者的静态文件?

我对输入的迭代变体感到厌烦,所以希望能提供一些背景知识。

谢谢!

您可以试试下面的代码:

    private readonly IWebHostEnvironment _hostingEnvironment;

    public HomeController(IWebHostEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    public IActionResult Index()
    {
       var path = Path.Combine(_hostingEnvironment.ContentRootPath, "WebContent/index.html");
       return PhysicalFile(path, "text/html");
    }