检查操作筛选器中的属性

Mat*_*rts 9 asp.net-core-mvc asp.net-core

在MVC 5中,您可以在其中执行类似的操作IActionFilter,以检查是否已在当前操作(或控制器范围)上声明属性

public void OnActionExecuting(ActionExecutingContext filterContext)
{
    // Stolen from System.Web.Mvc.AuthorizeAttribute
    var isAttributeDefined = filterContext.ActionDescriptor.IsDefined(typeof(CustomAttribute), true) ||
                             filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(CustomAttribute), true);

}
Run Code Online (Sandbox Code Playgroud)

因此,如果你的控制器像这样定义属性,这是有效的.

[CustomAttribute]
public ActionResult Everything()
{ .. }
Run Code Online (Sandbox Code Playgroud)

是否可以在ASP.NET Core MVC(内部IActionFiler)中执行相同的操作?

Anu*_*raj 9

是的,你可以做到.这是ASP.NET Core的类似代码.

public void OnActionExecuting(ActionExecutingContext context)
{
    var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
    if (controllerActionDescriptor != null)
    {
        var isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
            .Any(a => a.GetType().Equals(typeof(CustomAttribute)));
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

如果您需要检查属性,不仅需要检查某个方法,还需要检查 .NET Core 中的整个控制器,我是这样做的:

var controllerActionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor;

if (controllerActionDescriptor != null)
{
    // Check if the attribute exists on the action method
    if (controllerActionDescriptor.MethodInfo?.GetCustomAttributes(inherit: true)?.Any(a => a.GetType().Equals(typeof(CustomAttribute))) ?? false)
        return true;

    // Check if the attribute exists on the controller
    if (controllerActionDescriptor.ControllerTypeInfo?.GetCustomAttributes(typeof(CustomAttribute), true)?.Any() ?? false)
        return true;
}
Run Code Online (Sandbox Code Playgroud)