基于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相关问答推荐

即时窗口中的动态导致Microsoft.CSharp.RuntimeBinder.Binder未定义或导入错误

标签从右向左增长

在 C# 中将字符串转换为 colored颜色

Style 和 ControlTemplate 的区别

将屏幕捕获为位图

如何通过 LINQ 比较没有时间的 DateTime?

带有输入字段的消息框

C# 方法可以定义为采用的最大参数数是多少?

在 JavaScript 中使用 String.Format?

清除 .NET 的 StringBuilder 内容的最佳方法

如何对 LINQ to XML 中的元素进行深层复制?

如何正确和完全关闭/重置 TcpClient 连接?

是否可以完全用托管的 .NET 语言编写 JIT 编译器(本地代码)

实体框架中的 POCO 是什么?

Guid.Parse() 或 new Guid() - 有什么区别?

C# 应用程序中的全局键盘捕获

找不到 System.Windows.Media 命名空间?

System.IO.IOException:使用 System.IO.Path.GetTempFileName() 时文件存在 - 解决方案?

.NET 桌面应用程序中的 Settings.settings 与 app.config

捕获控制台退出 C#