<分区>
Possible Duplicate:
Why does my .NET Attribute not perform an action?
你好,
这听起来像是一个非常愚蠢的问题,我不知道这里有什么可能,因为网络上的所有“自定义属性”教程都几乎相同,而且它们没有解决我想做的事情。 我已经看到一些代码是在属性类中编写的,例如:Logging with ASP.NET MVC Action Filters我想知道这段代码是如何执行的。
例如,如果我有以下代码:
public class Test
{
[RestrictedAttribute("RegisteredMember")]
public void DoSomething()
{
//this code can only be executed if the logged-in user
//is a member of the RegisteredMember group
}
}
那么自定义属性 RestrictedAttribute 将是这样的:
[AttributeUsage(AttributeTargets.Method)]
public class RestrictedAttribute : System.Attribute
{
/// <summary>
/// Make this code restricted to users with a required role
/// </summary>
/// <param name="requiredRole">The role required to execute this method</param>
public RestrictedAttribute(string requiredRole)
{
//validate if member is in role, else throw exception
throw new MemberNotInRoleException(requiredRole);
}
public new string ToString() {
return "Access needs to be granted";
}
}
现在的问题是当我执行 Test.DoSomething() 方法时无法抛出 MemberNotInRoleException。
也许我只是错过了自定义属性的整个概念,请随意解释。