如何获取ASP.NET Core 8 Razor页面的文件夹路径?
获取ASP.NET Core 8 Razor Pages页面所在文件夹路径
针对你在Razor Pages中需要获取当前页面所在文件夹路径的需求,有两种可行方案:
方案一:利用框架内置的PageDescriptor(推荐)
Razor Pages的PageContext中包含ActionDescriptor(类型为PageActionDescriptor),其RelativePath属性直接存储了页面文件的相对路径(比如/App/ADMIN/Order/Details.cshtml)。通过Path.GetDirectoryName可以直接提取文件夹路径:
public class DetailsModel : PageModel { public void OnGet() { // 获取页面文件的相对路径 string pageRelativePath = PageContext.ActionDescriptor.RelativePath; // 提取文件夹路径,自动处理末尾斜杠 string folderPath = Path.GetDirectoryName(pageRelativePath) + Path.DirectorySeparatorChar; // 若需要拼接PathBase,可改为: // string fullFolderPath = $"{Request.PathBase}{Path.GetDirectoryName(pageRelativePath)}{Path.DirectorySeparatorChar}"; } }
这种方式依赖框架提供的元数据,比字符串处理更稳定,不受路由规则变化影响。
方案二:基于现有路由值的字符串处理
如果你想基于已有的RouteValues["Page"]逻辑实现,可以通过字符串截取获取文件夹路径:
public class DetailsModel : PageModel { private readonly IHttpContextAccessor _httpContextAccessor; // 注入IHttpContextAccessor(需在Program.cs中注册:builder.Services.AddHttpContextAccessor();) public DetailsModel(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } public void OnGet() { string pageRoute = _httpContextAccessor.HttpContext.Request.RouteValues["Page"] as string; if (!string.IsNullOrEmpty(pageRoute)) { int lastSlashIndex = pageRoute.LastIndexOf('/'); if (lastSlashIndex != -1) { string folderPath = $"{_httpContextAccessor.HttpContext.Request.PathBase}{pageRoute.Substring(0, lastSlashIndex + 1)}"; } } } }
这里的pageRoute值为/App/ADMIN/Order/Details,通过截取最后一个斜杠之前的部分,拼接PathBase即可得到目标文件夹路径。
内容的提问来源于stack exchange,提问作者Ryan Ong
相关产品推荐
相关产品推荐

