问题描述
我想获取我的 index.html 文件的虚拟路径,该文件位于我的 asp.net 核心 Web 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");
//...
}