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

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

问题描述

基于本文为ASP.NET Core创建 IActionFilter 实现,该实现可以处理在控制器和控制器的动作上标记的属性。尽管读取控制器的属性很容易,但我无法找到一种方法来读取在action方法上定义的属性。

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();
    }
}

我的问题是:如何阅读操作方法的

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

推荐答案

您可以访问 MethodInfo 通过 ControllerActionDescriptor 类:

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

public void OnActionExecuting(ActionExecutingContext context)
{
    var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
    if (controllerActionDescriptor != null)
    {
        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天全站免登陆