slolife
slolife

Reputation: 19870

How to add common code (specifically to methods marked WebMethod())

I have some ASP.NET page and webservice WebMethod() methods that I'd like to add some common code to. For example:

<WebMethod()> _
Public Function AddressLookup(ByVal zipCode As String) As Address
    #If DEBUG Then
        ' Simulate a delay
        System.Threading.Thread.Sleep(2000)
    #End If
    Return New Address()
End Function

I currently have the #If Debug code in all of my WebMethod() methods, but I am thinking there must be a better way to do this without having to actually type the code in.

Is there a way to determine if a request is to a WebMethod in Application_EndRequest so that I can add this delay project wide?

Note that some methods are Page methods and some are web service methods.

Upvotes: 0

Views: 432

Answers (2)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422252

Encapsulate the #if DEBUG code in a method and mark it with <Conditional("DEBUG")>. This way, you just write a method call in each <WebMethod>. Might be useful.

Upvotes: 1

M4N
M4N

Reputation: 96606

You can check the request URL in Application_EndRequest to determine whether it is a web method call. E.g. something like this (sorry it's in C#):

protected void Application_EndRequest(Object sender, EventArgs e)
{
  if (Request.Url.ToString().IndexOf("MyWebService.asmx") > 0)
  {
    // Simulate a delay
    System.Threading.Thread.Sleep(2000);
  }
}

Upvotes: 1

Related Questions