加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 03:55:43 所属栏目:百科 来源:网络整理
导读:对不起一个noob问题,但似乎我无法从Controller获取Server.MapPath.我需要从wwwroot的images文件夹输出json文件列表.他们是在wwwroot /图像.如何获得可靠的wwwroot路径? using System;using System.Collections.Generic;using System.Linq;using System.Thre
对不起一个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();
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读