gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:29:59 24 4
gpt4 key购买 nike

在我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com