Server Variables in ASP.NET

In this article we’ll explore the use of Server Variables array, a collection of information made available by IIS to ASPX pages.

These variables tell us details of the server environment in which the page is running. This can be valuable to us in a number of ways during the running of a web page script.

Let’s start by looking at what’s available. The listing below will display all the server variables in the Request.ServerVariables collection. The code below iterates through all of the items in the collection by using a For Each Next loop.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Page Language="VB" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Server Variables Demo</title>

<script runat="server">

Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim MyString As String =""
Dim name
MyString="<table><caption><strong>Server Variables Collection</strong></caption>"
For each name in Request.ServerVariables
MyString=MyString &"<tr><td>" & name &   "</td><td>" & Request.ServerVariables(name).ToString & "</td></tr>"
Next
MyString=MyString & "</table>"
Literal1.Text = MyString
End Sub

</script>

</head>

<body>
<form id="form1" runat="server">
<div>
<asp:Literal id="literal1" runat="server" />
</div>
</form>
</body>
</html>

Run the script above and you can see there’s a whole host of stuff there.

Let’s take a look at the more immediately useful ones.

The ALL_ variables are summaries of what is to be found elsewhere in the list. ALL_HTTP returns all the header information sent from the client when the page was retrieved, with each item prefixed by HTTP_, and the ALL_RAW string contains the same data without the HTTP_header name.

An immediate application might be to get some basic information about the visitors to your site. Whilst server logs usually record this, you might prefer to capture just what YOU want to know for visits.

Dim sBrowser As String = Request.ServerVariables("http_user_agent")
Dim sIPAddress As String = Request.ServerVariables("remote_addr")
Dim sResolvedAddress As String = Request.ServerVariables("remote_host")

This snippet of code stores the browser and originating IP address and resolved host name to string variables that can be used elsewhere in your application. For example, you might want to use the IP address to stop people voting more than once in an online poll, restrict access to specific IP addresses, etc.

I recently wrote a web application in which a page was used to run a SQL Stored Procedure and then return an XML file to the calling Javascript. Now, under some circumstances, the page was called with an HTTP GET and under other circumstances the page was called with an HTTP POST. I wanted to be able to elegantly grab parameters passed in to the script, so here’s what I did:

If Request.ServerVariables("REQUEST_METHOD ") = "GET" Then
sPolicyID = Request.QueryString("PolicyID")
Else
sPolicyID = Request.Form("PolicyID")
End If

The REQUEST_METHOD variable indicates whether a GET or POST HTTP request was used to call the page.

A related variable is QUERY_STRING. This variable returns the text on a GET request to the page that follows any ? on the request.

Note that the two variables LOGON_USER and REMOTE_USER are only useful if your site is running on a server with Windows Authentication enabled and enforced for the site. For most people, these variables will return empty strings.

If you want to find out what page is being displayed, PATH_INFO will return this e.g. '/mysite/default.aspx'. You might ask why this is useful, well it allows you to write ‘generic’ code for logging activity on the site, using this variable whenever you need to know what page you’re on. The related variable PATH_TRANSLATED resolves the page name into the full path and file name of the page on the server, e.g. 'c:\inetpub\www\mysite\default.asp'.

One interesting addition to ASP.NET has been the making available of server variables through the .NET Object Model. Rather than the variables being available through an array, they’re available as properties on .NET object. For example:

Dim filePath As String = System.Web.HttpContext.Current.Request.Path

Returns the same data as the PATH_INFO ServerVariable array entry.

Dim filePath As String = System.Web.HttpContext.Current.Request.PhysicalPath

Returns the same data as the PATH_TRANSLATED ServerVariable array entry.

This additional access model has two advantages in .NET.

1. Firstly, the object model exposes .NET specific variables for the developer that are not available in the normal ServerVariables array.  The Server Variables in the array, like PATH_TRANSLATED, are available and relevant to all languages running on the Web Server e.g. PHP and Perl as well as ASP.NET.  The object model allows exposure of properties of the .NET environment, like whether debugging is enabled on the site, to .NET languages only.

2. Secondly, the properties are strongly typed, there is no need to convert the PathInfo property to a string in the above, as it is already a string. The ServerVariables collection contents are always of type string, this might not always be appropriate and for some operations conversion between types might be needed. For example, dealing with CONTENT_LENGTH. In the ServerVariables array, CONTENT_LENGTH is still a string; on the HttpContext object the ContentLength property is an integer.

Whilst in VB.NET and ASP.NET, the operation Request.ServerVariables("CONTENT_LENGTH ") + 2 is legitimate and allowed, the language ‘guesses’ that you are wanting to add 2 to the length of the passed content, and does an ‘implicit conversion’ of the CONTENT_LENGTH string to an integer. A strongly typed .NET langauge such as C# would not allow this and would force you to convert the CONTENT_LENGTH variable to an integer. Having the integer version of this variable available on the HttpContext object removes the need for this conversion.

Read article on Practical uses of the ASP.NET Server Variables Collection

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

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

Get your best asp web hosting provider now and save 25%