[英]ASP.NET Core serving a file outside of the project directory
In my ASP.NET Core project I am trying to serve an html file like this: 在我的ASP.NET Core项目中,我尝试提供这样的html文件:
public IActionResult Index()
{
return File("c:/path/to/index.html", "text/html");
}
This results in an Error: 这将导致错误:
FileNotFoundException: Could not find file: c:/path/to/index.html
Pasting the path from the ErrorMessage into my browser I am able to open the file, so the file is clearly there. 将ErrorMessage的路径粘贴到我的浏览器中,我可以打开该文件,因此该文件显然位于此处。
The only way I have been able to serve the file is placing it in wwwroot in the project folder and serving it like this: 我能够提供文件的唯一方法是将其放置在项目文件夹的wwwroot中,并按以下方式提供文件:
public IActionResult Index()
{
return File("index.html", "text/html");
}
I have already changed the folder I serve static files from using app.UseStaticFiles(options)
(which works), so I figured the Controller would use that folder as default, but it keeps looking in wwwroot. 我已经使用app.UseStaticFiles(options)
更改了我为静态文件提供服务的文件夹(可以使用),因此我认为Controller会将该文件夹用作默认文件夹,但它会一直在wwwroot中查找。
How can I serve a file that is placed outside of wwwroot, or even outside the project, from a Controller? 如何从Controller为放在wwwroot甚至项目之外的文件提供服务?
You need to use PhysicalFileProvider
class, that is an implementation of IFileProvider
and is used to access the actual system's files. 您需要使用PhysicalFileProvider
类,该类是IFileProvider
的实现,用于访问实际系统的文件。 From File providers section in documentation: 从文档的“文件提供者”部分:
The PhysicalFileProvider provides access to the physical file system. PhysicalFileProvider提供对物理文件系统的访问。 It wraps the System.IO.File type (for the physical provider), scoping all paths to a directory and its children. 它包装System.IO.File类型(用于物理提供程序),对目录及其子目录的所有路径进行范围界定。 This scoping limits access to a certain directory and its children, preventing access to the file system outside of this boundary. 这种作用域限制了对某个目录及其子目录的访问,从而阻止了对该边界之外文件系统的访问。 When instantiating this provider, you must provide it with a directory path, which serves as the base path for all requests made to this provider (and which restricts access outside of this path). 实例化此提供程序时,必须为其提供目录路径,该目录路径用作对此提供程序进行的所有请求的基本路径(并且将访问限制在该路径之外)。 In an ASP.NET Core app, you can instantiate a PhysicalFileProvider provider directly, or you can request an IFileProvider in a Controller or service's constructor through dependency injection. 在ASP.NET Core应用中,您可以直接实例化PhysicalFileProvider提供程序,也可以通过依赖项注入在Controller或服务的构造函数中请求IFileProvider。
Example of how to create a PhysicalFileProvider
instance and use it: 如何创建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.