剃刀页面在单元测试中获取类属性

时间:2019-05-06 16:09:38

标签: .net-core razor-pages

当前,我正在尝试检查是否有一种方法来获取剃须刀页面类上所有属性的类名。 我对所有控制器进行单元测试以寻找AuthorizeFilter,以致无法忘记它

目前,这是我通过MVC进行的操作(在Razor Pages中不起作用):

var values = actionDescriptorCollectionProvider
.ActionDescriptors
.Items
.OfType<ControllerActionDescriptor>()
.Select(a => new
{
    a.DisplayName,
    a.ControllerName,
    a.ActionName,
    AttributeRouteTemplate = a.AttributeRouteInfo?.Template,
    HttpMethods = string.Join(", ", a.ActionConstraints?.OfType<HttpMethodActionConstraint>().SingleOrDefault()?.HttpMethods ?? new string[] { "any" }),
    Parameters = a.Parameters?.Select(p => new
    {
        Type = p.ParameterType.Name,
        p.Name
    }),
    ControllerClassName = a.ControllerTypeInfo.FullName,
    ActionMethodName = a.MethodInfo.Name,
    Filters = a.FilterDescriptors?.Select(f => new
    {
        ClassName = f.Filter.GetType().FullName,
        f.Scope //10 = Global, 20 = Controller, 30 = Action
    }),
    Constraints = a.ActionConstraints?.Select(c => new
    {
        Type = c.GetType().Name
    }),
    RouteValues = a.RouteValues.Select(r => new
    {
        r.Key,
        r.Value
    }),
});

问题是,此代码不适用于Razor Pages,即FilterDescriptors对于PageActionDescriptor为空。

1 个答案:

答案 0 :(得分:0)

您需要为RazorPages使用PageActionDescriptor而不是ControllerActionDescriptor

var values = actionDescriptorCollectionProvider
.ActionDescriptors
.Items
.OfType<PageActionDescriptor>()
.Select(descriptor => new
{
    // descriptor...,
    // ... 
});