簡體   English   中英

ASP.NET Core在項目目錄之外提供文件

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

在我的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的實現,用於訪問實際系統的文件。 文檔的“文件提供者”部分:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM