We are trying to create a more specific [Authorize] Attribute for Asp.Net MVC
[AttributeUsage(AttributeTargets.All)]
public class AuthoriseUser : System.Attribute
{
public AuthoriseUser(string PermRequest)
{
//Do Some Auth.
}
}
and we call this like so,
[AuthoriseUser("CanViewRoles")]
But when debugging the function is never called.
Now we are obviously doing somthing very wrong, I’ve seen PostSharp but due to the nature of the project I cant use it. How can i achieve this using just .Net?
Attributes are not meant for playing functional role. You need to write code using reflection somewhere in your project that reads type-meta-data of classes [and props, methods, etc.] and finds attributes applied to it. Based on the attributes applied you can take decisions at run-time about what to do with that. Generally this is done in base classes of your library.
As an example in our projects we have an attribute called ‘Searchable’. This attribute is applied to properties of business objects which need to be included in search. When the client calls Search method we filter out all props that are decorated with Searchable attribute and then construct query to do search on the database. Practically we dont have any code related to search functionality in SearchableAttribute class – in fact there’s no code at all in SearchableAttribute class.
Example Code:
SearchableAttribute
A method in business object base class