且构网

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

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

更新时间:2022-11-23 12:53:24

您可以通过 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.