Get wwwroot folder path from ASP.NET 5 controller VS 2015(从 ASP.NET 5 控制器 VS 2015 获取 wwwroot 文件夹路径)
问题描述
很抱歉提出一个菜鸟问题,但我似乎无法从 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 文件夹路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 ASP.NET 5 控制器 VS 2015 获取 wwwroot 文件夹路径
- 带问号的 nvarchar 列结果 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 使用 rss + c# 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
