Và cũng có thể, thay vì của tiêm IApplicationEnvironment
bạn có thể sử dụng PlatformServices.Default.Application.ApplicationBasePath
.
EDIT: Đây là một thực thể của MapPath/UnmapPath như phần mở rộng để PlatformServices
:
removed (see EDIT2)
EDIT2: Hơi sửa đổi, IsPathMapped()
thêm cũng như một số kiểm tra để xem nếu bản đồ path/unmapping là thực sự cần thiết.
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)
{
// todo: take it from project.json!!!
var result = Path.Combine(services.Application.ApplicationBasePath, "wwwroot");
return result;
}
}
EDIT3:PlatformServices.WwwRoot()
trở lại con đường thực hiện thực tế và trong lõi .net 2.0, chế độ DEBUG nó là xxx \ bin \ Debug \ netcoreapp2.0, trong đó, rõ ràng không phải là những gì được yêu cầu. Thay vào đó, hãy thay thế PlatformServices
bằng IHostingEnvironment
và sử dụng environment.WebRootPath
.
Nguồn
2016-02-17 14:44:31
'MapPath' là một phần của ASP.NET. –
Bạn có thể sử dụng thuộc tính ApplicationBasePath trên dịch vụ IApplicationEnvironment để lấy đường dẫn gốc của ứng dụng của bạn ... tò mò, kịch bản mà bạn đang cố gắng đạt được là gì? –
@KiranChalla Nó hoạt động, tuyệt vời, cảm ơn bạn! Nếu bạn muốn, xin vui lòng viết nó như là một câu trả lời và tôi sẽ chấp nhận nó :) Và liên quan đến câu hỏi của bạn - Tôi muốn xây dựng cấu trúc cơ sở dữ liệu của tôi (bảng, chức năng, vv) trên một máy chủ khởi động. –