C# · 12月 27, 2021

c# – 从ASP.NET 5控制器VS 2015获取wwwroot文件夹路径

对不起一个noob问题,但似乎我无法从Controller获取Server.MapPath.我需要从wwwroot的images文件夹输出json文件列表.他们是在wwwroot /图像.如何获得可靠的wwwroot路径? using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNet.Mvc;using www.Classes;using System.Web;namespace www.Controllers{ [Route(“api/[controller]”)] public class ProductsController : Controller { [HttpGet] public IEnumerable<string> Get() { FolderScanner scanner = new FolderScanner(Server.MapPath(“/”)); return scanner.scan(); } }}

Server.MapPath似乎从System.Web命名空间中不可用.

项目正在使用ASP.NET 5和dotNET 4.6 Framework

解决方法 您将需要将IHostingEnvironment注入到您的类中以访问ApplicationBasePath属性值:阅读约 Dependency Injection.成功注入依赖关系后,wwwroot路径应该可用.例如: private readonly IHostingEnvironment _appEnvironment;public ProductsController(IHostingEnvironment appEnvironment){ _appEnvironment = appEnvironment;}

用法:

[HttpGet] public IEnumerable<string> Get() { FolderScanner scanner = new FolderScanner(_appEnvironment.ApplicationBasePath); return scanner.scan(); }