如何从decorator方法中获取decorator对象

本文关键字:decorator 获取 对象 方法 | 更新日期: 2023-09-27 18:04:25

. 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
    }
}

CustomAuthorizeAttribute是System.Web.Mvc.AuthorizeAttribute的子类

如何从decorator方法中获取decorator对象

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

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;
        }

属性不是每个实例,它们是每个类,所以没有CustomAuthorizeAttribute的"当前"实例。参见属性的文档。

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

如果你需要获得CustomAuthorizeAttribute,你可以使用反射来获取关于你所在的类的信息,然后拉出属性的属性,但我会质疑你为什么需要这样做。你有什么特别需要我们帮忙的吗?

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