Asp.net-Core

檢查操作過濾器中的屬性

  • May 25, 2021

在 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);

}

因此,如果您的控制器像這樣定義屬性,則此方法有效。

[CustomAttribute]
public ActionResult Everything()
{ .. }

是否可以在 ASP.NET Core MVC 中(在 內IActionFiler)做同樣的事情?

是的,你可以做到。這是 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)));
   }
}

如果您需要檢查屬性,不僅是方法,還需要 .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;
}

引用自:https://stackoverflow.com/questions/44199347