Header add


In this tutorial we will learn how to get base path in .NET Core. As you know the static files are stored in .NET Core "wwwroot" folder, 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 ASP.NET Core, the physical paths to both the content root and the web root directories can be retrieved via the IWebHostEnvironment service. Below are the structure of .NET Core

└── aspnetcore-path
    └── src
        └── AspNetCorePath.Web
            ├── Controllers
            ├── Models
            ├── Properties
            ├── Views
            ├── bin
            ├── obj
            ├── wwwroot
            ├── Program.cs
            ├── Startup.cs
            ├── appsettings.Development.json
            ├── appsettings.json
            └── AspNetCorePath.Web.csproj


Let's create a .NET Core web application and we retrieve the content root and wwwroot path.
In many ways we can get this result.
  1. Constructor Injection in Controller
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 GetBasePath
}
public IActionResult Index()
{
return View();
}
}
The _hostingEnv object in the constructor of HomeController is used for getting the application root path and content root path. When we run the application the output should like this


  1. Constructor Injection in Startup.cs
public Startup(IConfiguration configuration,IHostingEnvironment _env)
{
Configuration = configuration;
string sAppPath = _env.ContentRootPath; //Application Base Path
string swwwRootPath = _env.WebRootPath; //wwwroot folder path
}
view raw Startup.cs hosted with ❤ by GitHub
In startup class you can also implement IHostingEnvironment and get the same result.




 
  Summary
   In this tutorial we discussed how to get application base path in Asp.Net Core. If have any question related to this topic then give your feedback.
Previous Post Next Post