如何在生产和开发环境中一致地获取 ASP.NET 5 DNX 项目的应用程序基础路径?
How to consistently get application base path for ASP.NET 5 DNX project on both production and development environment?
我已将 ASP.NET MVC 6 网站从 Git 部署到 Azure。部署的细节可以在 this blog post 中找到,但基本上我使用 DNU 发布它,然后 kudu 将它推送到 Azure 网站。
使用 IHostingEnvironment
我得到了 ApplicationBasePath。问题是我返回的路径在本地主机和 Azure 上非常不同。
蔚蓝:"D:\home\site\approot\src\src"
本地主机:"C:\Users\deebo\Source\mysite\site\src"
我想使用基本路径获取包含一些图像的文件夹的完整路径:wwwroot/img/gallery/
我使用以下代码解决了这个问题:
var rootPath = _appEnvironment.ApplicationBasePath;
var pathFix = "../../../";
if(_hostingEnvironment.IsDevelopment())
{
pathFix = string.Empty;
}
var imagesPath = Path.Combine(rootPath, pathFix, "wwwroot", "img", "gallery");
这可能有效,但看起来很老套。
我的部署方法是否会对此产生影响?
有没有更一致的获取应用程序路径的方法?
您可以使用 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.
这样就可以得到wwwroot路径甚至直接映射一个路径:
var wwwrootPath = env.WebRootPath;
var imagesPath = hostingEnv.MapPath("img/gallery");
PS。我在本地尝试过,而不是在 Azure 上。但是我还没有发现任何关于 Azure 问题的提及。 This answer 甚至提到在 Azure 中 IHostingEnvironment.WebRootPath
将指向 D:/Home/site/wwwroot
。
我已将 ASP.NET MVC 6 网站从 Git 部署到 Azure。部署的细节可以在 this blog post 中找到,但基本上我使用 DNU 发布它,然后 kudu 将它推送到 Azure 网站。
使用 IHostingEnvironment
我得到了 ApplicationBasePath。问题是我返回的路径在本地主机和 Azure 上非常不同。
蔚蓝:"D:\home\site\approot\src\src"
本地主机:"C:\Users\deebo\Source\mysite\site\src"
我想使用基本路径获取包含一些图像的文件夹的完整路径:wwwroot/img/gallery/
我使用以下代码解决了这个问题:
var rootPath = _appEnvironment.ApplicationBasePath;
var pathFix = "../../../";
if(_hostingEnvironment.IsDevelopment())
{
pathFix = string.Empty;
}
var imagesPath = Path.Combine(rootPath, pathFix, "wwwroot", "img", "gallery");
这可能有效,但看起来很老套。
我的部署方法是否会对此产生影响?
有没有更一致的获取应用程序路径的方法?
您可以使用 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.
这样就可以得到wwwroot路径甚至直接映射一个路径:
var wwwrootPath = env.WebRootPath;
var imagesPath = hostingEnv.MapPath("img/gallery");
PS。我在本地尝试过,而不是在 Azure 上。但是我还没有发现任何关于 Azure 问题的提及。 This answer 甚至提到在 Azure 中 IHostingEnvironment.WebRootPath
将指向 D:/Home/site/wwwroot
。