c# - ASP.NET Core 提供项目目录外的文件

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

在我的 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 的实现,用于访问实际系统的文件。来自 File providers文档部分:

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.

如何创建和使用 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

关于c# - ASP.NET Core 提供项目目录外的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43391812/

相关文章:

c# - 自托管 WCF 服务的跨域访问?

c# - DbParameterCollection不包含AddWithValue的定义

asp.net core mvc 中的 CKEditor 数据绑定(bind)

javascript - 删除行后提交动态表单的问题

c# - Azure 函数-Microsoft.AspNetCore.Server.Kestrel.Core : Request body too large

macos - 如何在azure中访问我的项目的文件

c# - 如何在 DNX Core 5.0 (ASP.NET 5) 中引用执行程序集?

java - 在没有第 3 方库的情况下在 Java 中使用 C# DLL

c# - 求一个数的平方的公式

c# - 如何等到所有请求都完成