UPDATE: IHostingEnvironment is deprecated. See update below.
In Asp.NET Core 2.2 and below, the hosting environment has been abstracted using the interface, IHostingEnvironment
The ContentRootPath property will give you access to the absolute path to the application content files.
You may also use the property, WebRootPath if you would like to access the web-servable root path (www folder by default)
You may inject this dependency into your controller and access it as follows:
public class HomeController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public ActionResult Index()
{
string webRootPath = _hostingEnvironment.WebRootPath;
string contentRootPath = _hostingEnvironment.ContentRootPath;
return Content(webRootPath + "
" + contentRootPath);
}
}
UPDATE - .NET CORE 3.0 and Above
IHostingEnvironment has been marked obsolete with .NET Core 3.0 as pointed out by @amir133. You should be using IWebHostEnvironment instead of IHostingEnvironment. Please refer to that answer below.
Microsoft has neatly segregated the host environment properties among these interfaces. Please refer to the interface definition below:
namespace Microsoft.Extensions.Hosting
{
public interface IHostEnvironment
{
string EnvironmentName { get; set; }
string ApplicationName { get; set; }
string ContentRootPath { get; set; }
IFileProvider ContentRootFileProvider { get; set; }
}
}
namespace Microsoft.AspNetCore.Hosting
{
public interface IWebHostEnvironment : IHostEnvironment
{
string WebRootPath { get; set; }
IFileProvider WebRootFileProvider { get; set; }
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…