Rewrite URLs on the Fly (Classic ASP)

Use HttpContext.RewritePath to “fake” URLs within an application.

One of the more obscure – but potentially useful – methods in the portion of the .NET Framework that comprises ASP.NET is the HttpContext class’s RewritePath method. Used internally by ASP.NET to strip session IDs from URLs when cookieless session state is enabled, RewritePath can also be used to “fake” URLs within an application. To demonstrate, consider the following ASPX file, which we’ll call RewritePath.aspx:

<h2><asp:Label ID=”Output” RunAt=”server” /></h2>

void Page_Load (Object sender, EventArgs e)
string id = Request.QueryString[“ID”];
if (id != null && id != String.Empty) {

switch (id) {

case “1”:

Output.Text = “Give me chastity and ” + “continence, but not yet.”;

case “2”:

Output.Text = “A programmer is a device ” + “for turning coffee into code.”;

case “3”:

Output.Text = “Blessed is the man who, ” + “having nothing to say, abstains from ” + “giving wordy evidence of the fact.”;




If this page is deployed in a virtual directory named Foo, then the following URLs invoke the page and display three different quotations:

So far, so good. Now suppose that you’d like users to be able to display these quotations by typing the following “phantom” URLs:


You can accomplish this little bit of magic – converting a URL of the form …/quotes/page1.aspx into a URL of the form …/rewritepath.aspx?id=1 on the fly – with HttpContext.RewritePath. The trick is to grab each request for /quotes/page1.aspx, /quotes/page2.aspx, and so on as it enters ASP.NET’s HTTP pipeline and convert it into a request for /rewritepath.aspx?id=1, /rewritepath.aspx?id=2, and so on. Here’s a Global.asax file that does just that:

void Application_BeginRequest (Object sender, EventArgs e)
// TODO: Convert a path of the form
// …/quotes/page1.aspx into a path of the form
// …/rewritepath.aspx?id=1

HttpContext context = HttpContext.Current;

string oldpath = context.Request.Path.ToLower ();
string token = “/quotes/page”;
int i = oldpath.IndexOf (token);
int len = token.Length;
if (i != -1) {

int j = oldpath.IndexOf (“.aspx”);
if (j != -1) {

string id = oldpath.Substring (i + len, j – (i + len));
string newpath = oldpath.Replace (token + id + “.aspx”, “/rewritepath.aspx?id=” + id);
context.RewritePath (newpath);



Application_BeginRequest fires at the beginning of every request. This implementation extracts the path portion of the URL targeted by the request (for example, /foo/quotes/page1.aspx), replaces it with a path that refers to the real page (for example, /foo/rewrite.aspx?id=1), and calls RewritePath to retarget the request. Try it: Drop RewritePath.aspx into wwwroot on your Web server and try to invoke it by typing this URL into your browser’s address bar:


That should generate a “page not found” error. Now copy Global.asax to wwwroot and try again. This time, it should work just fine, thanks to the indirection afforded by Application_BeginRequest.

RewritePath has many applications. You can use it, for example, to convert query strings into path names so pages that use query string parameters to drive content can be bookmarked in browsers. You can also use it to obfuscate path names within your application for security reasons. Now that you know RewritePath exists, you may find other uses for it, too.

By Jeff Prosise


Formatting numbers with Classic ASP

Format Numbers – Reference

Frequently you want a number to appear in a certain format. The most commands requests are for a set total number of digits and a set number of digits to the right of the decimal place. Less frequently there is a call for negative amounts displayed in parenthesis or that there should be leading zeros.

The FormatNumber function takes the contents of a number type variable and returns the contents in the specified format.

Syntax: FormatNumber(expression, iDigits, bleadingDigit, bParen, bGroupDigits)

argument meaning
expression the variable holding the raw number
iDigits number of digits to right of decimal point
bleadingDigit 1 for leading zeros
0 for no leading zeros
bParen 1 for parenthesis around negative numbers
0 for no parenthesis around negative numbers
bGroupDigits 1 to display numbers as per regional settings in the Control Panel
0 to over-ride settings in the Control Panel

</head><body bgcolor=”#FFFFFF”>
 My ASP formatting number sample
response.write “<hr>” & mynumber & “<br>”
response.write “formatnumber(mynumber,0)” & “<br>”
response.write formatnumber(mynumber,0) & “<hr>”
response.write “formatnumber(mynumber,2)” & “<br>”
response.write formatnumber(mynumber,2) & “<hr>”
response.write “formatnumber(mynumber,6)” & “<br>”
response.write formatnumber(mynumber,6) & “<hr>”

response.write mynumber & “<br>”
0 means means no leading zeroes
response.write “formatnumber(mynumber,2,0)” & “<br>”
response.write formatnumber(mynumber,2,0) & “<hr>”
1 means means pad with leading zeroes
response.write “formatnumber(mynumber,2,1)” & “<br>”
response.write formatnumber(mynumber,2,1) & “<hr>”

response.write mynumber & “<br>”
0 means means no parentheses for negative numbers
response.write “formatnumber(mynumber,2,0,0)” & “<br>”
response.write formatnumber(mynumber,2,0,0) & “<hr>”
1 means means yes parentheses for negative numbers
response.write “formatnumber(mynumber,2,0,1)” & “<br>”
response.write formatnumber(mynumber,2,0,1) & “<hr>”

Displaying Table Data with Classic ASP

This page demonstrates the capabilities how to display a table from a SQL statement.


<body bgcolor=”#FFFFFF”>
 this code opens the database
set conntemp=server.createobject(“adodb.connection”) myDSN

 this code retrieves the data
mySQL=”select * from publishers where state=NY
set rstemp=conntemp.execute(mySQL)

 this code detects if data is empty
If  rstemp.eof then
response.write “No records matched<br>”
response.write mySQL & “<br>So cannot make table…”
set connection=nothing
end if
<table border=1>
 This code puts fieldnames into column headings
response.write “<tr>”
for each whatever in rstemp.fields
response.write “<td><B>” & & “</B></TD>”
response.write “</tr>”

 Now lets grab all the records
DO  UNTIL rstemp.eof
 put fields into variables
company_name=rstemp(“company name”)

 write the fields to browser
cellstart=”<td align=””top””>”
response.write “<tr>”
response.write cellstart & pubid & “</td>”
response.write cellstart & name & “</td>”
response.write cellstart & company_name & “</td>”
response.write cellstart & address & “</td>”
response.write cellstart & city & “</td>”
response.write cellstart & state & “</td>”
response.write cellstart & zip & “</td>”
response.write cellstart & telephone & “</td>”
response.write cellstart & fax & “</td>”
response.write cellstart & comments & “</td>”

response.write “</tr>”

 Now close and dispose of resources
set rstemp=nothing
set conntemp=nothing


Select Case in Classic ASP

Using IF-THEN can be cumbersome, prone to programmer errors and slower to execute. A more efficient construct is SELECT CASE. It is optimized for testing one variable against many conditions.

</head><body bgcolor="#FFFFFF">
<form action="case2respond.asp" method="get">
Your First Name<INPUT NAME="FirstName" MaxLength=20><p>
Your Last Name<INPUT NAME="LastName" MaxLength=20><p>
Your Title
<INPUT TYPE="Radio" name="Title" VALUE="employee">Entry Level
<INPUT TYPE="Radio" name="Title" VALUE="temp" CHECKED>Temporary Employee
<INPUT TYPE="Radio" name="Title" VALUE="manager">Management Candidate
<INPUT TYPE="Radio" name="Title" VALUE="executive">Executive
<INPUT TYPE="Radio" name="Title" VALUE="vice-prez">The Vice President of...
<INPUT TYPE="Radio" name="Title" VALUE="CEO">The Boss<p>
<INPUT TYPE=submit><p>

Here is the select case that will determine what the form input means.

</head><body bgcolor="#FFFFFF">
response.write "Nice to Hire You " & fname & " " & lname & "<p>"
Select Case lcase(Title)
case "employee","temp"
response.write("The washroom is in the hall")
case "manager","executive"
response.write("Here is your key to the Executive washroom")
case "ceo", "vice-prez"
response.write("The maid will attend to your private washroom")
End Select%>

Add new record to the database using Classic ASP

Please note the code below. This sequence will add a new record into a database.

The database is identified by the DSN name and is called Student.

Option 1

The code below can be called by passing the parameteres in the query string like: dbnewrecSQL.asp?name=Joey&id=9000&year=1964

'on error resume next
If  auid<9000 then
end if
Set Conn = Server.CreateObject("ADODB.Connection") "DSN=Student;uid=student;pwd=magic"
SQLStmt = "INSERT INTO authors (AU_ID,author,year_born) "
SQLStmt = SQLStmt & "VALUES (" & auid
SQLStmt = SQLStmt & ",'" & auname & "'"
SQLStmt = SQLStmt & "," & int(auyear) & ")"
Set RS = Conn.Execute(SQLStmt)
set rs=nothing
If  err.number>0 then
response.write "VBScript Errors Occured:" & "<P>"
response.write "Error Number=" & err.number & "<P>"
response.write "Error Descr.=" & err.description & "<P>"
response.write "Help Context=" & err.helpcontext & "<P>"
response.write "Help Path=" & err.helppath & "<P>"
response.write "Native Error=" & err.nativeerror & "<P>"
response.write "Source=" & err.source & "<P>"
response.write "SQLState=" & err.sqlstate & "<P>"
response.write "No VBScript Errors Occured" & "<P>"
end if
IF  conn.errors.count> 0 then
response.write "Database Errors Occured" & "<br>"
response.write "<b>" & SQLstmt & "</b><P>"
for counter= 0 to conn.errors.count
response.write "Error #" & conn.errors(counter).number & "<P>"
response.write "Error desc. -> " & conn.errors(counter).description & "<P>"
response.write "No Database Errors Occured!" & "<P>"
end if
set conn=nothing

Option 2

This page demonstrates the capabilities how to add a record to a database using ADO instead of SQL. The script is:

<body bgcolor="#FFFFFF">
<% ' My ASP program that allows you to append a record %>
<form name="myauthor" action="dbnewADOrespond.asp" method="GET">
<p>Author ID: <input type="TEXT" name="id"></p>
<p> Author Name: <input type="TEXT" name="name"></p>
<p> Year Born: <input type="TEXT" name="year"></p>
<p> <input type="SUBMIT"> </p>

The form responder looks like this:

<body bgcolor="#FFFFFF">
<!--#INCLUDE VIRTUAL="/learn/test/lib_errors.asp" -->
on  error resume next
If  auid<9000 then
end if
Set RS = Server.CreateObject("ADODB.Recordset")
RS.Open "authors",Conn,adopenstatic,adlockoptimistic
RS("Author") = auname
RS("Year_Born")= int(auyear)
Call ErrorVBscriptReport("Adding Record")
Call ErrorADOReport("Adding Record",RS.activeconnection)
set rs=nothing