Razor Pages 中 wwwroot 下静态文件的路径

Meg*_*ez7 4 asp.net-core razor-pages

这3种方法有什么区别

  1. Directory.GetCurrentDirectory()
  2. Environment.CurrentDirectory
  3. hostingEnvironment.ContentRootPath

wwwroot用于获取存储在?下的图像的路径 在我的情况下,似乎所有的工作都是相同的,但我想了解它们之间是否存在任何其他具体情况的差异,或者使用其中一种的好处。

我使用此路径随后将图像加载到Bitmap MyBitmap变量中以进行进一步处理。希望它具有环境弹性,无论它最终部署到 Windows、Linux 还是容器;本地或云端。

将 Razor 页面与 ASP.NET Core 3.0 结合使用。

public class QRCodeModel : PageModel
{
  private readonly IHostEnvironment hostingEnvironment;

  public QRCodeModel(IHostEnvironment environment)
  {
     this.hostingEnvironment = environment;
  }

  public void OnGet()
  {
     string path1 = Path.Combine(Directory.GetCurrentDirectory(),
                                              "wwwroot", "img", "Image1.png");
     string path2 = Path.Combine(Environment.CurrentDirectory,
                                              "wwwroot", "img", "Image1.png");
     string path3 = Path.Combine(hostingEnvironment.ContentRootPath,
                                              "wwwroot", "img", "Image1.png");
  }
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*ind 6

还有另一种选择:

string TempPath4 = Path.Combine(hostingEnvironment.WebRootPath, "img", "Image1.png");
Run Code Online (Sandbox Code Playgroud)

WebRootPath返回 wwwroot 文件夹的路径。

建议使用前两个选项,因为它们可能不会返回您想要的位置:获取应用程序文件夹路径的最佳方法

  • 为了使用“WebRootPath”,必须使用“IWebHostEnvironment”而不是“IHostEnvironment”。 (2认同)