views:

651

answers:

1

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.

+1  A: 

The way you are looking at attributes sounds right at first, but think again. What you are really doing is decorating your class or whatever so that something that works with it can make a decision, not so that the class itself can make a decision. This was clouded for me by the way you can use actionfilter attributes in MVC, which look like they do something, but it is the framework which picks out events and uses the attribute accordingly. I usually try to think of attributes as comments for my program to work with.

Mark Dickinson