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
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.