简体   繁体   中英

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:

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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