asp.NET中使用include
By Steven Smith from aspalliance.com
A common way to build the navigation and layout for an ASP-driven website is to use include files. Most advanced ASP developers know that when you do this, it is best to encapsulate the functionality of the include file in a Sub or Function, and then to call this routine from the page that is including the file. This avoids problems with variable scope, allows parameters to be passed easily to the include file, and makes the code easier to read.
As these sites are migrated to use ASP.NET, it is likely that classic ASP and ASP.NET pages will exist side-by-side, which is one of the touted advantages of ASP.NET. Unfortunately, there is no built-in way for an ASP.NET page to take advantage of a classic ASP include file, which means that the obvious solution if you want to maintain a consistent look and feel is to duplicate the look of the classic ASP template in an ASP.NET user control. Unfortunately, this means duplicating presentation logic, and inevitably, the classic ASP template and the ASP.NET template will get out of sync.
To overcome this problem, I built a simple user control that uses ASP.NET's built-in page-scraping library, HTTPWebResponse, to grab a template ASP file and render it in my .aspx page. The template ASP file is simply a page that includes my presentation logic include file, and calls the functions to render the HTML, passing through any querystring parameters it has to those functions (such as for page title for a header include file).
For this demonstration, there are six files:
layout_sample.asp - this ASP page uses the include file the standard Classic ASP way.
header_include.asp - this is my actual ASP include file, which has a function called showHeader that will display the HTML for the page header wherever it is called. The page header is just an HTML table with the title of the page in it. The title is passed into showHeader as a required parameter.
header_template.asp - this is my template file. All it does is include my ASP header include file, call the showHeader function, and insert the querystring parameter for the title. If you click on this page, add "?title=foo" to the url to see how it uses the title from the querystring.
showHeader.ascx -- My user control that scrapes an ASP page to get the HTML to insert in my .aspx page.
showHeader.ascx.cs -- The code-behind file for my user control.
layout_sample.aspx - this ASP.NET page will use the Classic ASP layout
The Classic ASP example is very simple. All it does is include a file, call showHeader, and wrap it all in a basic HTML page:
1 <%Option Explicit%>
2 <!-- #INCLUDE FILE="header_include.asp" -->
3 <%
4 'Declare Variables
5 Dim title
6
7 title = "Sample Layout"
8 %>
9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
10 "">
11 <html>
12 <head>
13 <title><%=title%></title>
14 </head>
15 <body>
16 <% Call showHeader(title) %>
17 <p>
18 This is the main content of my sample Classic ASP page. Compare it to the
19 <a href="layout_sample.aspx">ASP.NET version</a>.
20 </p>
21 </body>
22 </html>
The include file is equally simple -- a single method that outputs some HTML. Note that this file can be called by either VBs cript or Js cript ASP pages, and avoids any context switching. It could also be called several times on one page, if need be.
1 <s cript runat="server" language="vbs cript">
2 Sub showHeader(title)
3 Response.Write "<table width=""100%"" bgcolor=""#CC0000"" border=""1"">"
4 Response.Write "<tr><td align=""center""><b>" & title & "</b></tr></td>"
5 Response.Write "</table>"
6 End Sub
7 </s cript>
Now let's take a look at the real "hack" part of this implementation, the dummy ASP page that is nothing more than a page that calls our include file (header_template.asp):
1 <%Option Explicit%>
2 <!-- #INCLUDE FILE="header_include.asp" -->
3 <% Call showHeader(Request("title")) %>
Finally, we can look at the user control that makes this whole thing work. It's pretty simple. All it does is use the HTTPRequest object that is built into ASP.NET to grab the header_template.asp page and insert it into the ASP.NET page. Something similar could be done with the ASPHTTP object in Classic ASP. Here's the file:
showHeader.ascx
1 <%@ Control language="c#" src="showHeader.ascx.cs"
2 Inherits="ASPAlliance.UserControls.showHeader" %>
3 <%@ OutputCache Duration="3600" VaryByParam="none" %>
4 <!-- Header Cached: <%=System.DateTime.Now%> -->
5 <asp:literal id="header" runat="server"/>
showHeader.ascx.cs
1 namespace ASPAlliance.UserControls
2 {
3 using System;
4 using System.IO;
5 using System.Net;
6 using System.Text.RegularExpressions;
7 using System.Web;
8 using System.Web.UI;
9 using System.Web.UI.WebControls;
10
11 public abstract class showHeader : System.Web.UI.UserControl
12 {
13 // Declare Controls
14 protected System.Web.UI.WebControls.Literal header;
15 public String title = "";
16
17 public showHeader(){
18 this.EnableViewState = false;
19 }
20
21 private void Page_Load(object sender, System.EventArgs e)
22 {
23 header.Text = readHtmlPage ("?title=" +
24 title + "&" +
25 Request.ServerVariables["QUERY_STRING"]);
26 header.Text = Regex.Replace(header.Text,
27 "</title>",
28 title + "</title>");
29 header.Text = Regex.Replace(header.Text,
30 "/libraryaspa/SSheader.asp",
31 Request.ServerVariables["URL"]);
32 }
33
34 private String readHtmlPage(string url)
35 {
36 WebResponse objResponse;
37 WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
38 objResponse = objRequest.GetResponse();
39 StreamReader sr = new StreamReader(objResponse.GetResponseStream());
40 return sr.ReadToEnd();
41 }
42 }
43 }
44
45
46
This is really pretty straightforward. In the page_load of the control, we grab use the HTTPWebResponse object to scrape the contents of header_template.asp, passing it our public property, page_title. We then suck in the result and display it in an asp:label tag. You might think this would be just atrociously slow, but in practice it works reasonably well. Throw a page-level output cache on your .aspx page, and any performance problems you might encounter disappear anyway. The only issue I've run into thus far is that sometimes images just don't show up through the web-scraper. This usually happens with larger images, so I think it has something to do with the scraper (HTTPWebResponse) object running out of time before it needs to return.
To conclude this example, let's take a look at one last page, the ASP.NET file that uses this control:
1 <%@ Page Language="C#" Trace="False" %>
2 <%@ Register TagPrefix="SSTemplate" tagname="showHeader" src="showHeader.ascx"%>
3 <%@ OutputCache Duration="100" VaryByParam="*" %>
4 <s cript runat="server">
5 String page_title = "Sample ASP.NET Layout";
6 void Page_Load(Object Src, EventArgs E){
7 // you can set the title here programatically
8 header.title = page_title;
9 // or down below we could declaratively add title="Sample ASP.NET Layout" to our tag.
10 }
11 </s cript>
12 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
13 "">
14 <html>
15 <head>
16 <title><%=page_title%></title>
17 </head>
18 <body>
19 <SSTemplate:showHeader id="header" runat="server" />
20 <p>
21 <p>
22 This is the main content of my sample ASP.NET page. Compare it to the
23 <a href="layout_sample.asp">Classic ASP version</a>.
24 </p>
25 </p>
26 </body>
27 </html>
This page is written in C#, just because I can, and also demonstrates how ASP.NET allows for easy code interoperability. In this case I have a C# page invoking a VB.NET user control. In fact, I'm even using a Classic ASP VBs cript method via an ASP include file, although somewhat indirectly!
By using this user control, you can maintain a single location for your site's layout templates, rather than having to maintain two sets of layout files. Once all of your .asp files are converted to .aspx files, your controls are already in place and you can simply delete your .asp templates and includes and move the layout HTML into your controls directly. Hope this helps!