Possible Duplicate:
Why does my .NET Attribute not perform an action?
Hi,
This may soundlike a very dumb question and I don't know what is possible here as all the "custom attribute" tutorials on the net are pretty much the same and they don't address what I want to do. I've seen some code out there where code is written inside attribute classes, eg: Logging with ASP.NET MVC Action Filters and I am wondering how this code is ever executed.
If I have for example the following code:
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
}
}
Then the custom Attribute RestrictedAttribute would be something like this:
[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";
}
}
Now the problem is that I can't get the MemberNotInRoleException to be thrown when I execute the Test.DoSomething() method.
Perhaps I am just missing the entire concept of custom attributes, feel free to explain.