说我在Index
的正下方有一个Pages
页面。在该页面的上下文中,我可以访问存储页面路径的PageContext.ActionDescriptor.ViewEnginePath
,并获取/Index
。
如何获取页面上下文之外的任何特定页面的视图引擎路径? ASP.NET Core是否为我可以访问的所有可用页面/视图维护一个带有视图引擎路径的集合?
这是一个ASP.NET Core 2.2应用程序。
答案 0 :(得分:0)
我有以下剃刀页面,用于调试所有路由信息。您可以按原样使用,也可以抓住_actionDescriptorCollectionProvider.ActionDescriptors.Items
并查找所需的特定值。
.cs代码:
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
namespace RouteDebugging.Pages {
public class RoutesModel : PageModel {
private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
public RoutesModel(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) {
this._actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
}
public List<RouteInfo> Routes { get; set; }
public void OnGet() {
Routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items
.Select(x => new RouteInfo {
Action = x.RouteValues["Action"],
Controller = x.RouteValues["Controller"],
Name = x.AttributeRouteInfo?.Name,
Template = x.AttributeRouteInfo?.Template,
Constraint = x.ActionConstraints == null ? "" : JsonConvert.SerializeObject(x.ActionConstraints)
})
.OrderBy(r => r.Template)
.ToList();
}
public class RouteInfo {
public string Template { get; set; }
public string Name { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public string Constraint { get; set; }
}
}
}
使用cshtml页面可以在表格中很好地查看它:
@page
@model RouteDebugging.Pages.RoutesModel
@{
ViewData["Title"] = "Routes";
}
<h2>@ViewData["Title"]</h2>
<h3>Route Debug Info</h3>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Route Template</th>
<th>Controller</th>
<th>Action</th>
<th>Constraints/Verbs</th>
<th>Name</th>
</tr>
</thead>
<tbody>
@foreach (var route in Model.Routes) {
@if (!String.IsNullOrEmpty(route.Template)) {
<tr>
<td>@route.Template</td>
<td>@route.Controller</td>
<td>@route.Action</td>
<td>@route.Constraint</td>
<td>@route.Name</td>
</tr>
}
}
</tbody>
</table>