ASP.NET 2.0 中的URL 重寫技術[轉]
實現URL重寫的幾種方法?
l 利用Application_BeginRequest和HttpContext類的Rewrite方法重寫URL,這種方法比較簡單易懂易用。
l 開發ASP.NET Http Module來達到同樣的目的
l 開發ISAPI過濾器來截取請求完成重寫
在這裡,我們將就第一種方法來闡述URL重寫的實現
Application_BeginRequest 事件
它是HTTP管線處理被激發的第一個事件,是重寫URL的最佳地方
HttpContext 類
這個類包含有關Http的特定資訊,其中有Http Request,當然也有Response對像。
這個類裡面有一個Current靜態屬性,它裡麵包含當前應用程的資訊。RewritePath方法是重寫URL的關鍵。在2.0中有四個簽名:
public void RewritePath(string path);
public void RewritePath(string path, bool rebaseClientPath);
public void RewritePath(string filePath, string pathInfo, string queryString);
public void RewritePath(string filePath, string pathInfo, string queryString, bool setClientFilePath);
按步就搬
1. 建立一個C# Web Application工程
2. 開啟WEB設定檔,加入下列代碼
<appSettings>
<add key="productsSite" value="products"></add>
<add key="servicesSite" value="services"></add>
<add key="supportSite" value="support"></add>
</appSettings>
我們把相對應的檔案夾名稱放在這裡,在後面的代碼中將用到。
3. 在工程裡添加三個檔案夾,Products,Support Services
4. 在每個檔案裡面添加一個default.aspx頁面
5. 開啟Global.asax看看事件控制代碼
protected void Application_BeginRequest(object sender, EventArgs e)
6. 把下面的代碼加到上述事件裡:
string host, originalurl, newurl;
host = Request.Url.Host;
originalurl = Request.Url.PathAndQuery;
switch (host)
{
case "products.henryliu.com":
newurl = "~/" +
ConfigurationSettings.AppSettings["productsSite"]
+ originalurl;
break;
case "services.henryliu.com":
newurl = "~/" +
ConfigurationSettings.AppSettings["servicesSite"]
+ originalurl;
break;
case "support.henryliu.com":
newurl = "~/" +
ConfigurationSettings.AppSettings["supportSite"]
+ originalurl;
break;
default:
newurl = "~/" +
ConfigurationSettings.AppSettings["supportSite"]
+ originalurl;
break;
}
HttpContext.Current.RewritePath(newurl);
讓我們再來看看這段代碼:
首先我們用 Request.Url.Host 屬性得到主機名稱,如:support.henryliu.com,其次還要獲得當前路徑的查詢字串。Switch語句我們用來根據目前使用者的請求來判斷真正要執行的頁面請求。最後,我們調用RewritePath()方法重寫當前請求的URL。
總節:在這篇文章裡我們可以學習到怎樣用Application_BeginRequest 和HttpContext.RewritePah()來重寫URL。這是一個快速實現實際請求頁面和我們看到的URL不同的方法。