views:

422

answers:

2

Hi All

I have a HtmlHelper extension method that I would like to apply some logic to before execution. I suppose I'm looking for behaviour similar to Action Filters, abut I thought I could do this by applying an Attribute to a method without the need of a Filter Context.

This is my extension method:

[MyHelperAttribute]
public static string MyHelperMethod(this HtmlHelper html, string text)
{
    TagBuilder tag = new TagBuilder("a");

    return tag.ToString();
}

where this is the definition of the Attribute:

[AttributeUsage(AttributeTargets.Method)]
public class MyHelperAttribute: Attribute
{        
    public MyHelperAttribute()
    {
        // get user 
        // if user has permission, execute extension method
        // else return empty string
    }
}

The problem is that it's not firing. The code inside the MyHelperAttribute constructor never executes. Can somebody tell me why this isn't working or what I can do to get it to work?

On a side note, is this a decent way to manage the generation of secure links? Is there a better way?

Thanks

Dave

+2  A: 

That's not how attributes work. They simply provide some metadata at compile time. At runtime, some code could use Reflection to find the attribute. At that time, if there were a method on the attribute, it's possible you could run it to do something.

John Saunders
But isn't an Action Filter the same as an Attribute? The Action Filter provides runtime functionality, doesn't it? I was under the impression that attributes provided functionality ancillary to the execution of the method, not simply metadata.
DaveDev
@Dave, there's actually another object (ControllerActionInvoker class) in ASP.NET MVC which gets the attributes on an action before invoking it. So, it doesn't automatically happen as soon as you decorate an attribute to a method. Like John said, attributes just provide some metadata.
çağdaş
@Dave: Attributes have been in .NET since version 1.0. Action Filters are new.
John Saunders
A: 

If what you are trying to do is a add a link to the HTML based upon user security, then you should probably make it an extension method of HttpContext which gives you full access to all of the attributes of the current page, including the User context.

Payton Byrd