bevacqua
bevacqua

Reputation: 48476

How to analyze attribute on method call?

I have an object with several methods. Some of which are decorated with a [AuthenticationRequired] attribute. When, and how, should I be checking whether the callee is authenticated?

This is just a simple null check, but I don't know how to hook it to the actual method calls. I'm kind of lost here.

Do I:

  1. Use a StackFrame, determine the top-level method called on this class, and then figure out possible authentication issues?
  2. Include this check in every single method that has the attribute? What's the attribute good for, then?
  3. Somehow hook to all method calls on my class, figuring out whether they have the attribute?

The class structure is roughly:

public class Stuff
{
     public void ImFine()
     {
         CommonMethod("fine");
     }

     public void ImGood()
     {
         CommonMethod("good");
     }

     [AuthenticationRequired]
     public void ImTerrible()
     {
         CommonMethod("terrible", true); // not an optional parameter.
     }

     [AuthenticationRequired]
     public void ImDeceased()
     {
         CommonMethod("dead");
     }

     protected void CommonMethod(string state)
     {
         Console.WriteLine(string.Format("I feel {0}", state));
     }

     protected void CommonMethod(string state, bool pet)
     {
         if (pet)
         {
             Console.WriteLine(string.Format("My pet feels {0}", state));
         }
         else
         {
             Console.WriteLine(string.Format("I feel {0}", state));
         }
     }
}

Assume CommonMethod is barely more complex and one can't invoke the other (in order to have one method shared by every callee).

Upvotes: 0

Views: 300

Answers (1)

empi
empi

Reputation: 15881

Have you thought about aspect oriented programming? You may take a look at some of implementations, ie: PostSharp or Castle.

Upvotes: 1

Related Questions