如何从Controller类自定义属性中读取属性值

时间:2014-01-10 03:37:27

标签: c# attributes

我在控制器上定义了一个自定义属性来执行安全功能。我如何读取属性的值,例如

[NavAttribute(Navigation = "Home")]
public class HomeController : Controller
{
    [SharePointContextFilter]
    public ActionResult Index()
    {...

3 个答案:

答案 0 :(得分:0)

这行代码将为您提供类的属性。

typeof(HomeController).GetCustomAttributes(typeof(NavAttribute), true);

对于方法

typeof(HomeController).GetMethod("Index").GetCustomAttributes(typeof(SharePointContextFilter), true);

答案 1 :(得分:0)

阅读任何其他属性没有区别。

        Type myType = typeof(MyClass1);
        // Get the members associated with MyClass1.
        MemberInfo[] myMembers = myType.GetMembers();

        // Display the attributes for each of the members of MyClass1. 
        for(int i = 0; i < myMembers.Length; i++)
        {
            Object[] myAttributes = myMembers[i].GetCustomAttributes(true);
            if(myAttributes.Length > 0)
            {
                Console.WriteLine("\nThe attributes for the member {0} are: \n", myMembers[i]);
                for(int j = 0; j < myAttributes.Length; j++)
                    Console.WriteLine("The type of the attribute is {0}.", myAttributes[j]);
            }
        }

如果您正在寻找特定属性:

myMembers[i].GetCustomAttributes(typeof(AttributeClassName),true);

答案 2 :(得分:-1)

我确信这些类似于预处理程序指令,并且无法在运行时获取。你可以做类似的事情:

[OutputCache(
    NoStore = HttpContext.Current.IsDebuggingEnabled, 
    Duration=(HttpContext.Current.IsDebuggingEnabled)?0:15
)]
public ActionResult RenderSomething(int somethingID)
{
...
}

OR:

if DEBUG
    [OutputCache(
        NoStore = HttpContext.Current.IsDebuggingEnabled, 
        Duration = 0)]
#else
    [OutputCache(
        NoStore = HttpContext.Current.IsDebuggingEnabled, 
        Duration = 15)]    
#endif

我认为你不能在类函数实现中获得属性的值。