頁面調度採用了UrlRewrite技術,關於該技術的資料可以參考我轉寄的一篇文章:http://erpcrm.cnblogs.com/articles/232924.html
首先,讓我們建立一個網站(我使用的是 VWD 2005 Express BETA2)。
1、添加一個default.aspx ,
該表單不需要做什麼工作,它的存在只有一個意義,就是告訴IIS 把類似的請求(www.xxx.com/)轉過來,否則的話,ASP.NET是截獲不到這種請求的。
2、我們在哪截獲使用者的請求呢?
當然是Global.asax了(當然了,你可以把代碼放到Global.asax.cs中,或者自己實現IHttpModuler來達到類似的效果)。
代碼如下:
;Global.asax檔案,只有一行,可以看出具體的代碼檔案都在Global.asax.cs裡面
<%@ Application Language="C#" CodeBehind="Global.asax.cs" Inherits="Global" %>
Global.asax.cs檔案:using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public class Global : System.Web.HttpApplication
{
protected void Application_BeginRequest(Object sender, EventArgs e)
{
String appPath = Request.AppRelativeCurrentExecutionFilePath;
if (appPath.StartsWith("~/Admin/", true, null))
{
return;
}
if (appPath.Equals("~/WebResource.axd", StringComparison.OrdinalIgnoreCase))
{
return;
}
if (appPath.StartsWith("~/ApplicationTemplate/", StringComparison.OrdinalIgnoreCase))
{
return;
}
this.Context.RewritePath("~/ApplicationTemplate/DefaultTemplate.aspx");
}
}
從以上的代碼可以看出:
除那三個特殊的路徑外,其它的請求全部重寫到"~/ApplicationTemplate/DefaultTemplate.aspx",
那麼 DefaultTemplate.aspx 包含什麼呢?
讓我們建立一個檔案夾 ApplicationTemplate 在該檔案夾下建立一個web表單 DefaultTemplate.aspx。
只 是為了示範UrlRewrite,DefaultTemplate.aspx中你可以輸入一些簡單的內容,如:“這是一個預設的模版”;
這樣當我們請求“/default.aspx”時,呈現在我們面前的頁面是DefaultTemplate.aspx的內容。
不信?你先動手試試吧!
3、如果我們想 把 / 重寫到 ApplicatonTemplate/defaultTemplate.aspx,而把 /product/ 重寫到ApplicationTemplate/ProductTemplate.aspx,怎麼做呢?
首先我們在ApplicationTemplate檔案夾下,添加一個ProductTemplate.aspx。
我們可能會想到在 Global.asax.cs 的 Application_BeginReque方法裡再添加一個對路徑的判斷,顯然這是不靈活的。
怎麼更靈活呢?就讓我們來設計一個頁面調度引擎吧!
在這裡,我們叫他 ApplicationManager。
添加一個類檔案 ApplicationManager.cs , VWD提示我們要把它放到 App_Code目錄下,就按它說的辦吧!
該類有個方法叫 String GetNewPath(String oldPath);
我們要這個方法輸入“/ default.aspx”返回 “~/ApplicationTemplate/DefaultTemplate.aspx”,
輸入"/product/" 返回 “~/ApplicationTemplate/ProductTemplate.aspx”
如果輸入的是“/Admin”,還應該返回“/Admin”。
我們假定GetNewPath()方法有這個功能,那麼讓我們改造一下 :Applicaton_BeginReques;
protected void Application_BeginRequest(Object sender, EventArgs e)
{
String appPath = Request.AppRelativeCurrentExecutionFilePath;
String newPath = ApplicationManager.GetNewPath(appPath)
if(newPath != appPath)
{
this.Context.RewritePath(newPath);
}
}
今天先到這,我的下一篇文章會把源碼提供出來,也許會和本文中的不太一致,但意思不會差。