【问题标题】:How to get the decorator objects from inside the decorated method如何从装饰方法内部获取装饰器对象
【发布时间】:2015-07-23 19:22:33
【问题描述】:

在我的 ASP.NET MVC 4 控制器类中,我使用 CustomAuthorize 属性装饰了一些操作,因此访问权限仅限于某些角色。

我想从操作方法中获取角色,为此我需要装饰方法的 CustomAuthorize 属性。

我该怎么做?

我正在尝试做的示例代码如下:

public class TestController : Controller
{
    // Only the users in viewer and admin roles should do this
    [CustomAuthorize("viewer", "admin")]
    public ActionResult Index()
    {
        //Need CustomAuthorizeAttribute so I get the associated roles
    }
}

CustomAuthorizeAttributeSystem.Web.Mvc.AuthorizeAttribute 的子类。

【问题讨论】:

    标签: c# asp.net-mvc-4


    【解决方案1】:

    如果您想从该方法中获取属性,您可以这样做,例如使用反射:

    var atrb = typeof(TestController).GetMethod("Index")
                 .GetCustomAttributes(typeof(CustomAuthorizeAttribute), true)
                 .FirstOrDefault() as CustomAuthorizeAttribute;
    

    或用于当前方法;

    var atrbCurrentMethod = System.Reflection.MethodBase.GetCurrentMethod()
                    .GetCustomAttributes(typeof(CustomAuthorizeAttribute), true)
                    .FirstOrDefault() as CustomAuthorizeAttribute;
    

    或者更灵活的方式,如果您想稍后创建一个函数,如您在评论中所述:

    public CustomAuthorizeAttribute GetCustomAuthorizeAttribute() {
                return new StackTrace().GetFrame(1).GetMethod()
                    .GetCustomAttributes(typeof(CustomAuthorizeAttribute), true).FirstOrDefault() as CustomAuthorizeAttribute;
            }
    

    【讨论】:

    • 似乎您已删除并发布了新答案。它从使用堆栈跟踪更改为新方法。我使用了您的旧代码,将框架从 0 更改为 1,并使其成为单独的方法。如果我使用这种新方法,我怎样才能转到调用方法而不是当前方法,它与旧方法相比如何更好?
    • 有了这个修改,旧冷更好。但你可以看这里stackoverflow.com/questions/171970/… :)
    【解决方案2】:

    属性不是每个实例的,它们是每个类的,因此没有 CustomAuthorizeAttribute 的“当前”实例。请参阅有关属性的文档。

    https://msdn.microsoft.com/en-us/library/z0w1kczw.aspx

    如果您需要获取 CustomAuthorizeAttribute,您可以使用reflection 获取有关您所在类的信息,然后提取该属性的属性,但我会质疑您为什么需要这样做。您有什么具体的需要我们可以提供更多帮助的吗?

    【讨论】:

    • 谢谢你,这很有帮助,+1。然而,反射示例是针对类而不是方法的。乔治下面的那个是重点。
    【解决方案3】:

    为什么不使用Roles.GetRolesForUser(); 方法来获取用户拥有的所有角色?这应该与从反射解析属性值得到的结果相同。

    【讨论】:

    • 这行不通。一个用户也可以是其他角色,该方法没有被修饰。
    • 那么,我建议参考 George 或 Hammerstein 的答案
    猜你喜欢
    • 2020-01-02
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2020-01-11
    • 2011-10-30
    • 2019-02-03
    相关资源
    最近更新 更多