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

大兔子大兔子 提交于 2019-12-06 02:44:40

问题


In my ASP.NET Core project I am trying to serve an html file like this:

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.

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:

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.

How can I serve a file that is placed outside of wwwroot, or even outside the project, from a Controller?


回答1:


You need to use PhysicalFileProvider class, that is an implementation of IFileProvider and is used to access the actual system's files. From File providers section in documentation:

The PhysicalFileProvider provides access to the physical file system. It wraps the System.IO.File type (for the physical provider), scoping all paths to a directory and its children. 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.

Example of how to create a PhysicalFileProvider instance and use it:

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


来源:https://stackoverflow.com/questions/43391812/asp-net-core-serving-a-file-outside-of-the-project-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!