ASP.NET testing shortcut

I often find when developing an ASP.NET application that I want to set a number of variables when the application loads to make testing easier. I usually have a number of variables set in the Session_Start section of the global.asax.vb or in the Page_Load of the default.aspx page. This is a quick and easy way of setting things like the currently logged in user or other settings.

The problem with doing this is that if you forget to comment out or remove these entries prior to uploading the site live you can run into some rather large problems.

If found an excellent function in the Request.URL class that can help avoid this issue. The function is called IsLoopback. If you wrap  “If Request.URL.IsLoopback” around your variable setting code, it will only be run when you are running your code from within Visual Studio or from IIS using the http://localhostURL.

Example:

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
     ' Fires when the session is started      Session(SessionVariables.UserID) = 1      Session(SessionVariables.CustomerID) = 2 End Sub

Becomes

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
     ' Fires when the session is started
     If Request.URL.IsLoopback Then
          Session(SessionVariables.UserID) = 1
          Session(SessionVariables.CustomerID) = 2
     End If
End Sub

As you can see from the code, if you forget to remove or comment out this code when you upload it to your web server, the code will skip right over setting these variables.

I would only recommend this type of variable setting in the initial development/testing phase and it should be removed once your application is put live.

Leave a Reply