簡體   English   中英

獲取數據注釋的參數值

[英]Get parameter's value of a Data Annotation

目標

獲取數據注釋的參數值。

問題

我不知道語法。

場景

我的應用程序具有以下控制器:

[PermissionsFilter(Roles = "Administrator")]
public ActionResult Index()
{
    return View();
}

在我的應用程序中有以下方法:

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    return true;
}

我所需要的似乎很簡單: 如何在AuthorizeCore方法上獲取Administrator字符串? 是通過httpContext參數嗎?

知識焦點

AuthorizeCore在實現AuthorizeAttributePermissionFilters類中。 換句話說,我重寫AuthorizeCore的方法Authorize屬性來創建一個新的(PermissionFilters屬性)。

您需要使用反射將屬性應用於您的控制器操作。 下面是一個簡單而又骯臟的示例,說明如何執行此操作:

    private string GetPermissionFilerValue()
    {
        object[] attributes = typeof(YourControllerType).GetType().GetMethod("Index").GetCustomAttributes(typeof (PermissionFilterAttribute));

        return attributes[0].Roles;
    }

基本上,您需要獲取對控制器類型的引用,然后從中獲取對控制器上方法的引用。 一旦有了它,就可以使用MethodInfo對象的形式,使用GetCustomAttributes來獲取應用於方法的所有自定義屬性或特定類型的所有自定義屬性。 一旦有了屬性實例,就可以檢查Roles屬性。

正如我提到的,上面的示例非常快速且骯臟地演示了如何獲取特定方法的屬性實例。 您可能需要對其進行定制,以使其適合您的特定方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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