While working on the back-end sometimes you need to dynamically retrieve the physical path within your application. It is quite easy to get the application base path in Asp.Net Core.
In this article, I will use the built-it service to get the content-root path and application base path in Asp.Net Core.
First of all, Inject the IHostingEnvironment on the constructor and use it later.
Examine the code below and I will explain it in the next paragraph.
public class HomeController : Controller
private readonly IHostingEnvironment _hostingEnv = null;
string AppBasePath = null;
string ContentRootPath = null;
public HomeController(IHostingEnvironment HostingEnv)
_hostingEnv = HostingEnv;
AppBasePath = _hostingEnv.WebRootPath; //path to wwwroot
ContentRootPath = _hostingEnv.ContentRootPath; //path to aspnetcore_test
public ActionResult Index()
For demo purpose, I have created the sample project and named it as aspnetcore_test. Here in the Home controller, I have use Constructor Injection which is one of the techniques of dependency injection.
The _hostingEnv object in the constructor of HomeController is used for getting the application root path and content root path.
The output for :
_hostingEnv.WebRootPath = “../aspnetcore_test/aspnetcore_test/wwwroot”
_hostingEnv.ContentRootPath = “../aspnetcore_test/aspnetcore_test”
Later you can use them on other methods for your requirement.
Information: Prior to Asp.Net Core RC2, you have to use IApplicationEnvironment instead of IHostingEnvironment.
Thanks for passing by.
Have a great day.