When migrating applications from ASP to ASP.NET there may be situations where you would like to use some of the existing ASP code within ASP.NET pages. This how can we achieve to do so.
We can embed ASP pages within ASP.Net pages by suing screen-scraping mechanisms provided by the WebRequest and WebResponse classes, which are within the System.Net namespace. These two classes provide a request/response model for accessing data from Internet. Using the WebRequest class we can create a request to the asp page, which you need to embed within ASP.NET page. The WebResponse class is used to receive the response generated by the request. We then use the StreamReader class to get the contents of the response and display it on the screen.
All this functionality is encapsulated within a static method of a class as given in the code below. This static function accepts the name of the ASP page to be embedded. It gets response from the ASP page and returns the response content as a string.
public class ASPWithInASPNet
{
public static void GetASPResults(string AspPage)
{
try
{
//CHECK IF THE GIVEN PAGE NAME IS A URL
Regex objRegex = new Regex(@"^http\://[a-zA-Z0-9\-\.]+[a-zA-Z]{2,3}(/\S*)?$");
string StrPath;
//IF THE PAGE NAME IS URL
if(objRegex.IsMatch(AspPage))
{
StrPath = AspPage;
}
//IF THE PAGE NAME IS NOT A URL
else
{
Uri RequestURI = HttpContext.Current.Request.Url;
StrPath = RequestURI.Scheme+ "://" + RequestURI.Host +
HttpContext.Current.Request.ApplicationPath + "/";
StrPath = StrPath + AspPage;
}
//CREATE A REQUEST TO THE ASP PAGE
HttpWebRequest WebReq =
(HttpWebRequest)WebRequest.Create(StrPath);
// GET THE RESPONSE
WebResponse WebRes = WebReq.GetResponse();
StreamReader SR = new StreamReader(WebRes.GetResponseStream());
HttpContext.Current.Response.Write(SR.ReadToEnd());
}
catch(WebException Ex)
{
HttpContext.Current.Response.Write( Ex.Message);
}
}
}
This class can be used in any of you ASP.Net pages as shown in the sample below.
private void Page_Load(object sender, System.EventArgs e)
{
ASPWithInASPNet.GetASPResults("http://localhost/aspconvertProj/default.asp");
}
Note: This functionality can be used to embed not only ASP pages but also any web page like JSP, HTML etc.