如何从 asp.net 核心应用程序的 wwwroot 文件夹中获取文件的虚拟路径?

How to get the virtual path of File from wwwroot folder of asp.net core app?

我想获取 index.html 文件的虚拟路径,该文件位于 asp.net 核心网站 API 的 wwwroot 文件夹中。我附上了我的代码图片,它将解释这个问题的情况。

现在我只是使用它的完整路径,这不是使用这样的路径的方便方法,所以这就是为什么我想获得这个文件的虚拟路径,这样在任何其他服务器上我都不会遇到任何问题。

在您的控制器中注入 IHostingEnvironment 并使用其 WebRootPath 访问您的文件

using Microsoft.AspNetCore.Hosting;
//...

public class AccountController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;

    public AccountController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    //...

    string htmlFilePath = Path.Combine(_hostingEnvironment.WebRootPath, "EmailTemplate", "index.html");

    //...
}