Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consistently get application base path for ASP.NET 5 DNX project on both production and development environment?

I have deployed a ASP.NET MVC 6 website to Azure from Git. Details of the deployment can be found in this blog post but basically I use DNU to publish it and then kudu to push it to an Azure website.

Using IHostingEnvironment I get the ApplicationBasePath. The problem is that the paths I get back are very different on localhost and on Azure.

Azure: "D:\home\site\approot\src\src"
Localhost: "C:\Users\deebo\Source\mysite\site\src"

I want to use the base path to get the full path to a folder containing some images: wwwroot/img/gallery/

I got around this with the following code:

var rootPath = _appEnvironment.ApplicationBasePath;

var pathFix = "../../../";
if(_hostingEnvironment.IsDevelopment())
{
    pathFix = string.Empty;
}
var imagesPath = Path.Combine(rootPath, pathFix, "wwwroot", "img", "gallery");

This may work but seems hacky.

Is it possible my deployment method impacts on this?
Is there a more consistent way to get the application path?

like image 375
Devon Burriss Avatar asked Sep 17 '15 13:09

Devon Burriss


1 Answers

You can use the IHostingEnvironment.WebRootPath. From the Asp 5 deep dive:

The IHostingEnvironment services gives you access to the Web root path for your application (typically your www folder) and also an IFileProvider abstraction for your Web root.

So you can get the wwwroot path or even directly map a path:

var wwwrootPath = env.WebRootPath;
var imagesPath = hostingEnv.MapPath("img/gallery");

PS. I tried this locally, not on Azure. However I haven't found any mention about issues in Azure. This answer even mentions that in Azure IHostingEnvironment.WebRootPath will point to D:/Home/site/wwwroot.

like image 188
Daniel J.G. Avatar answered Nov 15 '22 23:11

Daniel J.G.