且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ASP.NET Core MVC中读取操作方法的属性?

更新时间:2022-11-23 12:58:19

您可以访问 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.