C # execute code inside custom attribute

Possible duplicate:
Why is my .NET attribute not performing an action?

Hello,

This may sound like a very stupid question, and I don’t know what is possible here, since all the "custom attribute" tutorials on the network are almost the same and they don’t affect what I want to do. I saw some code where the code is written inside the attribute classes, for example: Logging in with ASP.NET MVC Action Filters , and I wonder how this code is 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 will look 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 cannot get a MemberNotInRoleException when executing the Test.DoSomething () method.

, , .

+5
1

, . , , - - , -, , , , . , actionfilter MVC, , - , , . .

+2
source

All Articles