如何在 Asp.Net core API 中获取具有给定目录名称的字符串变量中的目录路径

How to get the directory path in a string variable having the given directory name in Asp.Net core API

我正在尝试获取 API 控制器中文件夹 'Images' 的完整路径名。但是以下语法不起作用。如果有人可以提供帮助,将不胜感激

string path = HttpContext.Current.Server.MapPath("~/Images/");

您不需要 System.Web 或 HttpContext。您可以从 IHostingEnvironment.WebRootPath in ASP.NET Core 2.x, or IWebHostEnvironment.WebPath in ASP.NET Core 3.x.

中读取 Web 应用程序的根路径

依赖注入机制知道该接口,这意味着您可以将其作为依赖项添加到您的控制器或服务中,例如:

public class MyController : Controller 
{
    private IWebHostEnvironment _hostingEnvironment;

    public MyController(IWebHostEnvironment environment) {
        _hostingEnvironment = environment;
    }

    [HttpGet]
    public IActionResult Get() {

        var path = Path.Combine(_hostingEnvironment.WebRootPath, "Images");
        ...
    }

您可以将根路径传递给 class 的构造函数。毕竟,一个名为 ImagesFilesRepository 的 class 只关心它的本地文件夹,而不关心它是托管在 Web 还是控制台应用程序上。为此,方法不应是静态的:

public class ImagesFilesRepository 
{

    public ImagesFilesRepository (string rootPath)
    {
        _rootPath=rootPath;
    }

    public DriveService GetService()
    {
         //Operations.... 

    public List<GoogleDriveFiles> GetDriveFiles()
    {
        // Other operations....
    }

}

您可以在 Startup.cs 中将 class 注册为服务:

public class Startup
{
    private readonly IWebHostEnvironment _env;

    public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {
        Configuration = configuration;
        _env = env;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSignleton<GoogleDriveFilesRepository>(_ =>{
            var gdriveRoot=Path.Combine(_env.WebRootPath,"GoogleDriveFiles");
            return new GoogleDriveFilesRepository(gdrivePath);
        });
        ...
    }
}

这个 class 现在可以用作对控制器的依赖。不再需要在控制器中使用 IWebHostEnvironment :

public class MyController : Controller 

{
    private ImagesFilesRepository _gdrive;

    public MyController(ImagesFilesRepository gdrive) {
        _gdrive=gdrive;
    }
}