基于this article,我正在try 为ASP.NET Core创建一个IActionFilter实现,它可以处理控制器上标记的属性和控制器的操作.尽管读取控制器的属性很容易,但我无法找到读取操作方法上定义的属性的方法.

以下是我现在掌握的代码:

public sealed class ActionFilterDispatcher : IActionFilter
{
    private readonly Func<Type, IEnumerable> container;

    public ActionFilterDispatcher(Func<Type, IEnumerable> container)
    {
        this.container = container;
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        var attributes = context.Controller.GetType().GetCustomAttributes(true);

        attributes = attributes.Append(/* how to read attributes from action method? */);

        foreach (var attribute in attributes)
        {
            Type filterType = typeof(IActionFilter<>).MakeGenericType(attribute.GetType());
            IEnumerable filters = this.container.Invoke(filterType);

            foreach (dynamic actionFilter in filters)
            {
                actionFilter.OnActionExecuting((dynamic)attribute, context);
            }
        }
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        throw new NotImplementedException();
    }
}

我的问题是:如何在ASP中读取操作方法的属性.网络核心MVC?

推荐答案

您可以通过ControllerActionDescriptor类访问动作的MethodInfo:

public void OnActionExecuting(ActionExecutingContext context)
{
    if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
    {
        var actionAttributes = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true);
    }
}

MVC5ActionDescriptor类用于实现ICustomAttributeProvider接口,该接口允许访问属性.由于某种原因,这在ASP中被删除.NET核心MVC ActionDescriptor类.

.net相关问答推荐

.NET Blazor-使用子组件中的处理程序方法进行双向数据绑定

如何在PowerShell中隐藏任务延迟输出?

PowerShell - 如果用户输入凭据,则查询 AD 时出错

为什么 .NET 中的 System.Version 定义为 Major.Minor.Build.Revision?

在 C# 中生成随机小数

在 web api 控制器(.net 核心)中使用 async/await 或任务

将 DataRowCollection 转换为 IEnumerable

Style 和 ControlTemplate 的区别

比较 C# 中的字符串和对象

在 .NET C# 中存储加密密钥的最佳方式

如何正确停止BackgroundWorker

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") 返回上午时间而不是下午时间?

变量MyException已声明但从未使用

.NET 反射的成本是多少?

如何比较 C# 中的(目录)路径?

.Net 正则表达式:单词字符 \w 是什么?

在 .NET Core 中在 MVC 之外使用 Razor

铸造:(NewType)与对象作为NewType

泛型类的默认构造函数的语法是什么?

如何将 MailMessage 对象作为 *.eml 或 *.msg 文件保存到磁盘