如何在 ASP.NET Core MVC 中读取操作方法的属性? [英] How to read action method's attributes in ASP.NET Core MVC?

查看:23
本文介绍了如何在 ASP.NET Core MVC 中读取操作方法的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于这篇文章我正在尝试为 ASP.NET Core 创建一个 IActionFilter 实现,该实现可以处理在控制器上标记的属性和控制器的操作.虽然读取控制器的属性很容易,但我无法找到读取操作方法上定义的属性的方法.

Based on this article I'm trying to create an IActionFilter implementation for ASP.NET Core that can process attributes that are marked on the controller and the controller's action. Although reading the controller's attributes is easy, I'm unable to find a way to read the attributes defined on the action method.

这是我现在拥有的代码:

Here's the code I have right now:

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.NET Core MVC 中读取 action 方法的属性?

My question is: how do I read the action method's attributes in ASP.NET Core MVC?

推荐答案

您可以通过 ControllerActionDescriptor 类:

You can access the MethodInfo of the action through the ControllerActionDescriptor class:

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

MVC 5 ActionDescriptor 类用于实现允许访问属性的 ICustomAttributeProvider 接口.出于某种原因,这在 ASP.NET Core MVC ActionDescriptor 类.

The MVC 5 ActionDescriptor class used to implement the ICustomAttributeProvider interface which gave access to the attributes. For some reason this was removed in the ASP.NET Core MVC ActionDescriptor class.

这篇关于如何在 ASP.NET Core MVC 中读取操作方法的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆