Skip to main content

Get application base and wwwroot path in ASP.NET Core RC2

In this short post, find out how to get application base and wwwroot path in ASP.NET Core RC2 as some of the stuffs changed compared to ASP.NET Core RC1.

Get application base and wwwroot path in ASP.NET Core RC2

You can get the application base path and wwwroot folder path from IHostingEnvironment service.

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    string sAppPath = env.ContentRootPath; //Application Base Path
    string swwwRootPath = env.WebRootPath;  //wwwroot folder path
    Configuration = builder.Build();
}

If you want to get the same in your controller, then define a constructor and inject IHostingEnvironment service and assign it to a variable. And then within any controller action method, use the variable to get application base path or wwwroot folder path.

IHostingEnvironment _env;
public ValuesController(IHostingEnvironment env)
{
    _env = env;
}
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
    return new string[] { _env.WebRootPath };
}

And if you are still using RC1, then you need to use IApplicationEnvironment service to get application base path and IHostingEnvironment service to get wwwroot folder path. In RC2, both are present in IHostingEnvironment service.

public Startup(IHostingEnvironment env, IApplicationEnvironment Appenv)
{
    // Set up configuration sources.
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json");

    string sAppPath = Appenv.ApplicationBasePath; //Application Base Path
    string swwwRootPath = env.WebRootPath;  //wwwroot folder path
    if (env.IsEnvironment("Development"))
    {
        builder.AddApplicationInsightsSettings(developerMode: true);
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build().ReloadOnChanged("appsettings.json");
}

Using the same sample code provided above, you can get them in any of your controller. Cheers!!!!

Also read, How to rename wwwroot folder in ASP.NET Core 1.0.

Thank you for reading and I hope it helped you. Keep visiting this blog and share this in your network.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

4 thoughts to “Get application base and wwwroot path in ASP.NET Core RC2”

Leave a Reply

Your email address will not be published. Required fields are marked *