可以通过结合反射和路由器,动态获取所有PageModel类的URL。
首先,我们需要引用Microsoft.AspNetCore.Mvc.ApplicationParts这个命名空间,以便获取我们当前应用程序中所有的部件。
然后,我们可以使用ApplicationPartManager对象获取我们当前应用程序中所有的部件。
接下来,我们可以寻找来自所有部件的类型,并找到继承自PageModel的那些类型。
最后,我们可以使用RazorPagesOptions对象中的Conventions属性,根据约定来获取URL。
示例代码如下:
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public static class RazorPagesExtensions
{
public static IEnumerable GetPageUrls(this ApplicationPartManager manager)
{
var pageUrlList = new List();
var feature = new ControllerFeature();
manager.PopulateFeature(feature);
foreach (var c in feature.Controllers)
{
if (typeof(PageModel).IsAssignableFrom(c))
{
var modelType = c.AsType();
var selectorModelType = typeof(PageRouteModelConvention).Assembly
.GetType("Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.Selectors.CompiledPageRouteModel");
var convention = new PageRouteModelConvention("{property", selectorModelType.GetField("Matcher").GetValue(null), true);
var actionMethods = modelType.GetTypeInfo().DeclaredMethods
.Where(a => a.IsPublic && !a.IsDefined(typeof(NonHandlerAttribute)));
foreach (var method in actionMethods)
{
var actionRouteModel = new PageActionDescriptor()
{
ModelTypeInfo = modelType.GetTypeInfo(),
ActionName = method.Name,
ReturnType = method.ReturnType,
Parameters = method.GetParameters()
.Select(p => new ParameterDescriptor()
{
Name = p.Name,
ParameterType = p.ParameterType,
BindingInfo = BindingInfo.GetBindingInfo(new[] { p })
}).ToList(),
RouteValues = new Dictionary(StringComparer.OrdinalIgnoreCase),
PropertyInfo = modelType.GetTypeInfo().Declared
上一篇:ASP.NETCoreRazorPages中如何编写自定义标签?
下一篇:Asp.NetCoreRazorPages中,当在PageModel上使用Authorize特性设置策略后,授权处理程序仍然在执行设置为文件夹的策略后运行。