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

3 c# directory directory-structure asp.net-web-api asp.net-core

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

这是我的代码的图像,请看这个

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

Ale*_*der 8

更新

注入IWebHostEnvironment您的控制器并使用它WebRootPath来访问您的文件

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

public class AccountController : Controller
{
    private readonly IWebHostEnvironment _hostingEnvironment;

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

    //...

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

    //...
}
Run Code Online (Sandbox Code Playgroud)

较旧 ASP.NET Core 版本的答案

注入IHostingEnvironment您的控制器并使用它WebRootPath来访问您的文件

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

public class AccountController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;

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

    //...
}
Run Code Online (Sandbox Code Playgroud)


Pur*_*han 8

到 2023 年,IHostingEnvironment您将不再像亚历山大响应那样使用IWebHostEnvironment和注入它。