Sunday, April 08, 2007

Transferring sessions from asp to aspx

          In my starting days with dotnet before 2 years, all vendors were converting from ASP to ASP.NET. They still wanted some of the pages in ASP. The real problem is to transfer session from asp page to aspx page.  The easiest way I found was shown below.

         Lest say that you have a page Old.asp and a page New.aspx . You need to transfer the session from Old to New. The idea is create an intermediate forms(pages)  that can help you in transferring the sessions.  First Create Step1.asp page and redirect to this page from "Old.asp" page . This page will creates a form with hidden fields which stores the value of all session variables as shown below,

<html>
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<
title>Step 1</title>
</
head>
<
body>
<%
Response.Write("<form name=t id=t action=Step2.aspx method=post >")
For each Item in Session.Contents
Response.Write("<input type=hidden name=" & Item)
Response.Write( " value=" & Session.Contents(item) & " >")
next
Response.Write("</FORM>")
Response.Write("<script>t.submit();</script>")
%>
</
body>
</
html>

Fig - (1) First Step to transfer the session from asp to aspx.


       The page shown in Fig - (1) creates the form will create new form which has action attribute set to "Step2.aspx" page. This page will loop through all the session variables and generates hidden field for each. After that, java script submit the page to aspx page. Now look at the "Step2.aspx" page.

public class WebForm1 : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
for(int i=0;i<Request.Form.Count;i++)
{
Session[Request.Form.GetKey(i)]=Request.Form[i].ToString();
}
// Destination aspx page to which you need to transfer sessions
Server.Transfer(Session["DestPage"].ToString(),true);

}
}

Fig - (2)  Step2 to transfer session from asp to aspx.


        This page will loop through all the fields of posted form using "Request.Form" and add the values in session. The last line transfer this aspx page to destination aspx page which is "New.aspx".


Happy Programming !

2 comments:

Ajeet said...

i am try it.
it will working only on IE.
but in case of Firefox it not transfer asp.net page.
can u tell me how i will do it in firefox.

Anonymous said...

Wasn't the original article published on EggHeadCafe.com? Maybe you should mention that, to avoid plagiarism claims...