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

那年仲夏 提交于 2019-12-22 03:40:54

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32631066/how-to-consistently-get-application-base-path-for-asp-net-5-dnx-project-on-both

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!