【问题标题】:Access a Method's Attribute from OnActionExecuting从 OnActionExecuting 访问方法的属性
【发布时间】:2018-10-24 05:30:36
【问题描述】:

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

我试过这个:

var methodAttr = Attribute.GetCustomAttribute(context.ActionDescriptor.GetType(), typeof(AuthorizeAttribute));

但我总是得到一个 Null 值。

也试过这个:

MethodBase method = MethodBase.GetCurrentMethod();
AuthorizeAttribute methodAttr = (AuthorizeAttribute)method.GetCustomAttributes(typeof(AuthorizeAttribute), true)[0];

但是当没有 AuthorizeAttribute 时,我得到一个超出范围的异常。

我该如何进行这项检查?

【问题讨论】:

    标签: c# .net-core asp.net-mvc-filters


    【解决方案1】:

    我根据您的标签假设这是针对 .net 核心的。 这是检查自定义属性的示例

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

    【讨论】:

    • 为简单起见 => descriptor.MethodInfo.GetCustomAttribute&lt;AuthorizeAttribute&gt;() != null
    • 请记住,我们也可以这样做 => descriptor.MethodInfo.IsDefined(typeof(AuthorizeAttribute))。我喜欢它,因为这里我们不需要自定义属性的值。对不起双厘米:)
    猜你喜欢
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 2021-11-16
    相关资源
    最近更新 更多