从 OnActionExecuting 访问方法的属性

San*_*oud 3 c# asp.net-mvc-filters .net-core

我想知道如何检查控制器方法是否具有特定属性,例如AllowAnonymous内部OnActionExecuting覆盖方法。

我尝试过这个:

var methodAttr = Attribute.GetCustomAttribute(context.ActionDescriptor.GetType(), typeof(AuthorizeAttribute));
Run Code Online (Sandbox Code Playgroud)

但我总是得到一个空值。

也尝试过这个:

MethodBase method = MethodBase.GetCurrentMethod();
AuthorizeAttribute methodAttr = (AuthorizeAttribute)method.GetCustomAttributes(typeof(AuthorizeAttribute), true)[0];
Run Code Online (Sandbox Code Playgroud)

但是,当没有 AuthorizeAttribute 时,我会收到超出范围的异常。

我怎样才能进行这项检查?

bhm*_*ler 5

I'm assuming based on your tags that this is for .net core. Here is an example of checking for a custom attribute

var descriptor = (ControllerActionDescriptor) context.ActionDescriptor;
if (descriptor.MethodInfo.GetCustomAttribute<AuthorizeAttribute>() != null) { 
    //Do something
}
Run Code Online (Sandbox Code Playgroud)

  • 为简单起见 =&gt; `descriptor.MethodInfo.GetCustomAttribute&lt;AuthorizeAttribute&gt;() != null` (2认同)
  • 请记住,我们也可以这样做 =&gt; `descriptor.MethodInfo.IsDefined(typeof(AuthorizeAttribute))`。我喜欢它,因为这里我们不需要自定义属性的值。抱歉有双重评论:) (2认同)