【问题标题】:ASP.NET Core serving a file outside of the project directoryASP.NET Core 为项目目录之外的文件提供服务
【发布时间】:2017-04-13 12:02:09
【问题描述】:

在我的 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) 提供静态文件的文件夹(有效),所以我认为控制器会默认使用该文件夹,但它一直在 wwwroot 中查找。

如何从控制器提供位于 wwwroot 之外甚至项目之外的文件?

【问题讨论】:

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

您需要使用PhysicalFileProvider 类,这是IFileProvider 的实现,用于访问实际系统的文件。来自文档中的File providers 部分:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    相关资源
    最近更新 更多