Practical uses of the ASP.NET Server Variables Collection

In a previous article we took a look at the ASP.NET Server variables collection. In this article, we?ll look at a few examples of the practical applications of these variables.

Simple Security

I?m a lucky chap in that I have a fixed IP address for my network. I look after a few sites where I have a password protected screen for management but I also wanted to put a little bit more protection on the page. In particular, I wanted to only be able to access the page when I logged in from my own network. To do this, I use the REMOTE_ADDR server variable.

The below listing shows a simple application that renders page content depending upon the IP address that the site was accessed from. There is also a simple logging routine that writes the address to a text file.

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Sub LogAccess() 
' This routine writes out a file in to the root of your
' web site with the name log.txt and then writes data
' to it. First of all set file name. Use Server.MapPath
' variable to get path to web site on server.

Dim sLogName As String = Server.MapPath("log.txt")
' Now set up a streamwriter, and open the stream to append text
' to it. If the file doesn’t exist, this will create the file
' when it first runs
Dim objStreamWriter As System.IO.StreamWriter
objStreamWriter = System.IO.File.AppendText(sLogName)
' Now write a line of text to the stream containig the IP Address
' and the current date and time.
objStreamWriter.WriteLine("IP Address: " & Request.ServerVariables("remote_addr") & " at " & DateTime.Now.ToString())
' Finally close the stream
objStreamWriter.Close()
End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<%
' Check the server variable and if it’s not from
' the IP address we’re expecting, deny access. Here
' the IP address is 127.0.0.1 – change to suit.
If Request.ServerVariables("remote_addr") <> "127.0.0.1" Then
LogAccess()
%>
<h1>Access Denied</h1>
<% Else
LogAccess()
%>
<h1>Management Page</h1>
<p>This is where my management page code would go!</p>
<%End If%>

</div>
</form>
</body>
</html>

Access Page Once

A further example using the same variable is shown below; here an IP address can only access the page once. This can be used in a simple voting application, but in the real world you would need to take account of the fact that many of your users will not have dedicated IP addresses.

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Function CheckAccess() As Boolean
Dim bFound As Boolean = False
Dim sIPAddress As String = Request.ServerVariables("remote_addr").ToString
Dim sLogName As String = Server.MapPath("log.txt")

' First of all get existing list and check it. Do this by
' opening the file and reading all the contents in to a
' single string, called ‘contents’. Then use the Instr()
' function to see if the IP address is already in it.
' NOTE – Try…Catch is used to deal with the first pass
' when the file won’t exist.
'

Try
Dim objStreamReader As System.IO.StreamReader
objStreamReader = System.IO.File.OpenText(sLogName)
Dim contents As String = objStreamReader.ReadToEnd()
If InStr(contents, sIPAddress) <> 0 Then
bFound = True
End If
objStreamReader.Close()
Catch

End Try

' Check to see if the IP address was in the file
' and if it wasn’t then open the file for append 
' as a streamwriter and write the IP address in to it.
If Not bFound Then
Dim objStreamWriter As System.IO.StreamWriter
objStreamWriter = System.IO.File.AppendText(sLogName)
objStreamWriter.WriteLine(" " & Request.ServerVariables("remote_addr"))
objStreamWriter.Close()
End If
Return bFound
End Function

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<% If CheckAccess() Then
%>
<h1>You've voted!</h1>
<% Else

%>
<h1>Voting Page</h1>
<p>This is where the vote code would go!</p>
<%End If%>

</div>
</form>
</body>
</html>

Where did that come from?

The HTTP_REFERER variable can be very useful when you?re trying to determine where a particular hit on a page on your site came from. For example, you might want to know whether you?re getting a lot of traffic from Google. Or, on a ?local? basis, you might want to know what page a user of your site was previously on to the page that the user is currently on ? you might decide to run some code if a user comes from one page on your site, and another page if they come from elsewhere.

The below code example keeps a file on your site listing where a user came to your site from. Note that the HTTP_REFERER variable is far from perfect. There are a number of situations where it doesn?t work properly, including Response.Redirects, handling a referral from a link in a program such as Outlook, running within a local ASP.NET development environment, etc.

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Sub LogRef()
Dim sRefAddress As String = Request.ServerVariables("HTTP_REFERER")
Dim sLogName As String = Server.MapPath("log.txt")
Dim sTmpName As String = Server.MapPath("tmp.txt")
Dim sLine As String
Dim sPair() As String

Dim objStreamWriter As System.IO.StreamWriter
Dim objStreamReader As System.IO.StreamReader

' First of all get existing list and check it. If we don't find the referrer then
' add it on the end of the line. Special case is where
' the Referer is blank – we’ll just write LOCAL
' as the referer in these cases.

If sRefAddress = "" Then sRefAddress = "LOCAL"
Try
' Open two files, one for reading (the existing log)
' and one for being written to (sTmpName)
objStreamWriter = System.IO.File.AppendText(sTmpName)

objStreamReader = System.IO.File.OpenText(sLogName)
' Read through the log file a line at a time.

While objStreamReader.Peek() <> -1
' read line in
sLine = objStreamReader.ReadLine()
' Split line apart at a comma
sPair = Split(sLine, ",")
' First entry in array will now have referer name and
' second has count of referals from that referer.
' If referer is the same then increment count.
If sRefAddress = sPair(0) Then
Dim iCount As Integer = Convert.ToInt32(sPair(1)) + 1
' Now write the line to the Tmp file.
objStreamWriter.WriteLine(sRefAddress & "," & iCount.ToString())
Else
' Get here and it’s a new referer so write out the
' referer name with a zero.
objStreamWriter.WriteLine(sRefAddress & ",0")
End If
End While

' Close the files.
objStreamReader.Close()
objStreamWriter.Close()

Catch
' If first time, start a new file by writing the
' referer name and 1 to the Tmp file.
Dim iCount As Integer = 1
objStreamWriter.WriteLine(sRefAddress & "," & iCount.ToString())
objStreamWriter.Close()
End Try
 
' Now delete old Log file, copy new tmp file to be
' the log file and delete the tmp file.

System.IO.File.Delete(sLogName)
System.IO.File.Copy(sTmpName, sLogName)
System.IO.File.Delete(sTmpName)
End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">

<div>
<% LogRef()
%>
<h1>Referer Logged</h1>
</div>

</form>
</body>
</html>

Get the best ASP hosting with DiscountASP.NET - great value, money back guarantee.

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.

Global ASP.NET Hosting Leader - Click Here