ASP.NET Core为项目目录之外的文件提供服务

在我的ASP.NET核心项目中,我试图像这样提供一个html文件:

public IActionResult Index() { return File("c:/path/to/index.html", "text/html"); } 

这会导致错误:

 FileNotFoundException: Could not find file: c:/path/to/index.html 

将ErrorMessage的路径粘贴到我的浏览器中,我可以打开文件,因此文件显然就在那里。

我能够提供文件的唯一方法是将它放在项目文件夹中的wwwroot中,并按照以下方式提供:

 public IActionResult Index() { return File("index.html", "text/html"); } 

我已经使用app.UseStaticFiles(options)更改了我提供静态文件的文件夹app.UseStaticFiles(options) ,所以我认为Controller会将该文件夹用作默认文件,但它会继续查找wwwroot。

如何从Controller中提供位于wwwroot之外,甚至是项目之外的文件?

您需要使用PhysicalFileProvider类,它是IFileProvider的实现,用于访问实际系统的文件。 从文档中的文件提供程序部分:

PhysicalFileProvider提供对物理文件系统的访问。 它包装System.IO.File类型(对于物理提供程序),确定目录及其子目录的所有路径。 此作用域限制了对某个目录及其子目录的访问,从而阻止了对此边界之外的文件系统的访问。 在实例化此提供程序时,必须为其提供目录路径,该路径充当对此提供程序发出的所有请求的基本路径(并限制此路径之外的访问)。 在ASP.NET Core应用程序中,您可以直接实例化PhysicalFileProvider提供程序,也可以通过依赖项注入在Controller或服务的构造函数中请求IFileProvider。

有关如何创建PhysicalFileProvider实例并使用它的示例:

 IFileProvider provider = new PhysicalFileProvider(applicationRoot); IDirectoryContents contents = provider.GetDirectoryContents(""); // the applicationRoot contents IFileInfo fileInfo = provider.GetFileInfo("wwwroot/js/site.js"); // a file under applicationRoot