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

问题描述 投票:0回答:2

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

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

api asp.net-core asp.net-web-api directory directory-structure
2个回答
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");

    //...
}

旧版 ASP.NET Core 版本的解答

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

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

public class AccountController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;

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

    //...
}

8
投票

在 2023 年,您将使用

IHostingEnvironment
代替
IWebHostEnvironment
,并像亚历山大响应一样注入。

© www.soinside.com 2019 - 2024. All rights reserved.