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

3

本文介绍了从 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 文件夹路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14