1

I am building a Web Service API to provide remote access data from a management system.

There are various functions in the API and all require an access key.

I am currently wrapping the insides of all functions like this:

Function GETSOMETHING(api_key)
    If IntegratedApis.Grant_Api_Access(api_key) Then
        /// DO STUFF
    Else
        Return "API KEY not provided or incorrect"
    End
 End Function

Obviously my IntegratedApis.Grant_Api_Access(api_key) function returns a boolean output and checks the user's key in the database

This works, but the problem is it's a bit of a maintenance pain. How can I automatically wrap this around ALL calls to the webservice?

Is it possible via the global.asax file to return the error on Application_BeginRequest for example?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jamie Hartnoll
  • 7,231
  • 13
  • 58
  • 97

1 Answers1

0

Look for Aspect Oriented Programming (AOP) frameworks for .NET. These frameworks basically intercept all calls and run them through a function that relies heavily on reflection.

For example:

// Original function call that you want routed through AOP.
[KeyCheck]
public void OriginalFunctionCall() {
     ...
}

// AOP function that accepts all functions that were decorated with [KeyCheck].
// Runs logic before the function, runs the function, runs logic after.
public void Intercept() {
    // Before original function.
    keyCheck();

    // Original function
    functionCall();

    // Logic after original function.
    cleanUp();
}

Some of the frameworks let you put an annotation on all calls you want routed through the AOP framework. When I've used this approach, you have any logic you want performed before your call executed, then the call is executed, then any logic you want performed after the original call.

Some .NET AOP frameworks:

Last note: Be careful with performance. Some of the frameworks - since they use reflection heavily - can slow down your code.

Community
  • 1
  • 1
ryan1234
  • 7,237
  • 6
  • 25
  • 36