some of my controller actions require a user to be authenticated. Those actions are flagged with a custom [Authorize] attribute. Behind the scene, a custom membership provider does some magic, among which setting some temporary data into the common-thread.
At the end of each action that required an authentication, a call to the OnActionExecuted() filter is required to cleanup the thread. This is done via another custom attribute called [CleanupContext].
So my actions look like this:
[Authorize]
[CleanupContext]
public ViewResult Action()
{
...
}
Since those two are always used together, since I am lazy and since I fear that someday one dev might forget to put one or the other and we end up with some weird behavior: is there a way to combine them into one attribute?
[AuthorizeAndCleanup]
public ViewResult Action()
{
// Aaah, if only it could look like this :D
}
Thanks a lot!
You could derive from
AuthorizeAttributein order to do your custom authorization stuff and implementIActionFilterin order to have access to theOnActionExecutingandOnActionExecutedevents (to do your custom cleanup code):Obviously you should be aware that neither the
OnActionExecutingor theOnActionExecutedevents will ever be executed if the authorization fails (a.k.a. theAuthorizeCoremethod returns false) so make sure you do your cleanup in this method if you are about to return false.