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 文件夹路径
基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
