问题描述
很抱歉提出一个菜鸟问题,但我似乎无法从 Controller 获取 Server.MapPath.我需要从 wwwroot 的图像文件夹中输出 json 文件列表.它们位于 wwwroot/images.如何获得可靠的 wwwroot 路径?
Sorry for a noob question, but it seems I can't get Server.MapPath from Controller. I need to output json file list from images folder at wwwroot. They are is at wwwroot/images. How can I get a reliable wwwroot path?
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 命名空间中不可用.
Server.MapPath seems not available from System.Web namespace.
项目正在使用 ASP.NET 5 和 dotNET 4.6 框架
Project is using ASP.NET 5 and dotNET 4.6 Framework
推荐答案
您需要将 IWebHostEnvironment
注入到您的类中才能访问 ApplicationBasePath
属性值:阅读关于依赖注入.成功注入依赖后,wwwroot 路径 应该可供您使用.例如:
You will need to inject IWebHostEnvironment
into your class to have access to the ApplicationBasePath
property value: Read about Dependency Injection. After successfully injecting the dependency, the wwwroot path should be available to you. For example:
private readonly IWebHostEnvironment _appEnvironment;
public ProductsController(IWebHostEnvironment appEnvironment)
{
_appEnvironment = appEnvironment;
}
用法:
[HttpGet]
public IEnumerable<string> Get()
{
FolderScanner scanner = new FolderScanner(_appEnvironment.WebRootPath);
return scanner.scan();
}
IHostingEnvironment
在 asp.net 的更高版本中已被 IWebHostEnvironment
取代.
IHostingEnvironment
has been replaced by IWebHostEnvironment
in later versions of asp.net.
这篇关于从 ASP.NET 5 控制器 VS 2015 获取 wwwroot 文件夹路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!