Mag*_*ian 15 c# asp.net rest asp.net-core-mvc asp.net-core
很抱歉有一个noob问题,但似乎我无法从Controller获取Server.MapPath.我需要从wwwroot的images文件夹输出json文件列表.他们是在wwwroot/images.我怎样才能获得可靠的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
System.MapPath似乎在System.Web命名空间中不可用.
Project正在使用ASP.NET 5和dotNET 4.6 Framework
Olu*_*emi 23
您将需要注入IHostingEnvironment
到您的类中以访问ApplicationBasePath
属性值:阅读有关依赖注入的信息.成功注入依赖项后,您应该可以使用wwwroot路径.例如:
private readonly IHostingEnvironment _appEnvironment;
public ProductsController(IHostingEnvironment appEnvironment)
{
_appEnvironment = appEnvironment;
}
Run Code Online (Sandbox Code Playgroud)
用法:
[HttpGet]
public IEnumerable<string> Get()
{
FolderScanner scanner = new FolderScanner(_appEnvironment.ApplicationBasePath);
return scanner.scan();
}
Run Code Online (Sandbox Code Playgroud)
Chi*_*gum 21
我知道这已经得到了解答,但根据我的托管环境(IIS Express与IIS),它给了我不同的结果.如果您想获得wwwroot路径,以下方法似乎适用于所有托管环境(请参阅此GitHub问题).
例如
private readonly IHostingEnvironment _hostEnvironment;
public ProductsController(IHostingEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}
[HttpGet]
public IEnumerable<string> Get()
{
FolderScanner scanner = new FolderScanner(_hostEnvironment.WebRootPath);
return scanner.scan();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18522 次 |
最近记录: |