![](/img/trans.png)
[英]Decorator Pattern : How to withdraw additional responsibilities from a decorated object ?
[英]How to get the decorator objects from inside the decorated method
在我的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
}
}
CustomAuthorizeAttribute
是System.Web.Mvc.AuthorizeAttribute的子类。
属性不是按实例,而是按类,因此CustomAuthorizeAttribute没有“当前”实例。 请参阅有关属性的文档。
https://msdn.microsoft.com/en-us/library/z0w1kczw.aspx
如果需要获取CustomAuthorizeAttribute,则可以使用反射来获取有关您所在类的信息,然后提取该属性的属性,但是我会问为什么需要这样做。 您是否需要特定的东西,我们可以提供更多帮助?
如果要从该方法获取属性,则可以执行此操作,例如,使用反射:
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;
}
为什么不使用Roles.GetRolesForUser();
方法来获取用户拥有的所有角色? 这应该具有与从Reflection解析属性值中获得的结果相同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.