Home > MonoRail > Clean controllers with custom attributes

Clean controllers with custom attributes

It might be an obvious thing to do, but sometimes you miss the most obvious approaches…

Instead of repeatedly typing (copy and pasting!) [Filter(ExecuteEnum.BeforeAction, typeof(AuthenticationFilter)] for every controller you want to apply (in my case) the AuthenticationFilter to, spend 5 minutes building a custom attribute to do the work for you (I place these attribute classes in the same file as the filter):

public class ApplyAuthenticationFilterAttribute : FilterAttribute
{
    public ApplyAuthenticationFilterAttribute() : base ( ExecuteEnum.BeforeAction, typeof(AuthenticationFilter)
    {
    }
}

Now you leverage the IDE to do all the work for you (intellisense and code completion are the smart programmers copy / paste), and even if you only use it on one base controller, you still get the benefit of a nice attribute that you don’t even have to think about to understand…
[ApplyAuthenticationFilter]
public class MyController : Controller
{
    ...
}

vs
[Filter(ExecuteEnum.BeforeAction, typeof(AuthenticationFilter)]
public class MyController : Controller
{
    ...
}

The same approach can be used with layouts and rescues making your controllers “read” nicely
[UseDefaultLayout, UseGeneralError, ApplyAuthenticationFilter]
public class MyController : Controller
{
    ...
}

Advertisement
Categories: MonoRail

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.