繁体   English   中英

ASP.NET Core在项目目录之外提供文件

[英]ASP.NET Core serving a file outside of the project directory

在我的ASP.NET Core项目中,我尝试提供这样的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)更改了我为静态文件提供服务的文件夹(可以使用),因此我认为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

暂无
暂无

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

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