此外,你可以使用PlatformServices.Default.Application.ApplicationBasePath
代替注入IApplicationEnvironment
。
编辑: 这里是将MapPath/UnmapPath作为PlatformServices
的扩展可能的实现:
removed (see EDIT2)
编辑2: 稍作修改,添加了IsPathMapped()
,并进行了一些检查以确定是否真正需要路径映射/取消映射。
public static class PlatformServicesExtensions
{
public static string MapPath(this PlatformServices services, string path)
{
var result = path ?? string.Empty;
if (services.IsPathMapped(path) == false)
{
var wwwroot = services.WwwRoot();
if (result.StartsWith("~", StringComparison.Ordinal))
{
result = result.Substring(1);
}
if (result.StartsWith("/", StringComparison.Ordinal))
{
result = result.Substring(1);
}
result = Path.Combine(wwwroot, result.Replace('/', '\\'));
}
return result;
}
public static string UnmapPath(this PlatformServices services, string path)
{
var result = path ?? string.Empty;
if (services.IsPathMapped(path))
{
var wwwroot = services.WwwRoot();
result = result.Remove(0, wwwroot.Length);
result = result.Replace('\\', '/');
var prefix = (result.StartsWith("/", StringComparison.Ordinal) ? "~" : "~/");
result = prefix + result;
}
return result;
}
public static bool IsPathMapped(this PlatformServices services, string path)
{
var result = path ?? string.Empty;
return result.StartsWith(services.Application.ApplicationBasePath,
StringComparison.Ordinal);
}
public static string WwwRoot(this PlatformServices services)
{
var result = Path.Combine(services.Application.ApplicationBasePath, "wwwroot");
return result;
}
}
EDIT3: PlatformServices.WwwRoot()
返回实际执行路径,在 .net core 2.0 DEBUG 模式下,它是 xxx\bin\Debug\netcoreapp2.0,显然不是所需的。取而代之的是,将
PlatformServices
替换为
IHostingEnvironment
并使用
environment.WebRootPath
。
MapPath
是 ASP.NET 的一部分。 - Daniel A. White