簡體   English   中英

如何從裝飾方法內部獲取裝飾對象

[英]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
    }
}

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM