In ASP.NET Core Razor Pages, how do I get the view engine path of a page outside the page context?
Yura Gorokhovsky
Say I'm Index
in Pages
. In the context of that page, I can access PageContext.ActionDescriptor.ViewEnginePath
the /Index
.
How can I get the view engine path of any particular page outside the page context? Does ASP.NET Core maintain a collection of view engine paths to all available pages/views that I can access?
This is an ASP.NET Core 2.2 application.
Brad Patton
I have the following razor page for debugging all route information. You can use as is or get _actionDescriptorCollectionProvider.ActionDescriptors.Items
and find the specific value you are looking for.
.cs code:
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; }
}
}
}
View it nicely in a table using a cshtml page:
@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>