我們有時候會見到這樣的地址:“http://www.huoho.com/show-12-34.html”,你或許認為在站台伺服器根目錄“/”下存在名為“show-12-34.html”的檔案,其實實際它可能是不存在的,而可能你看到的內容是 “/aspx/show.aspx?type=12&id=34”的內容,為什麼要這樣做呢?原因有多個方面:首先是增強URL的友好性,記 “show-12-34.html”總比“/aspx/show.aspx?type=12&id=34”好記吧?其次就是方便搜尋引擎收錄,很多搜尋引擎更看好靜態HTML頁,比如:百度;其次就是出於安全性的考慮,因為這樣隱藏了參數“type”、“id”。是不是很有意思呢?
其實這是利用URL重寫實現的,下面我就說一下在ASP.NET2.0下我所知道的最簡單的實現方法:通過實現介面“IHttpHandler”來接管HTTP請求,Follow me!
1.在資源管理方案中添加一個類,類的代碼如下:
引用內容//類URLRewriter程式清單:
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;
/// <summary>
/// UrlRewriter URL重寫類
/// Author:yoyo
/// blog:http://yangmingsheng.cn/
/// </summary>
public class UrlRewriter : IHttpHandler //實現“IHttpHandler”介面
{
public UrlRewriter()
{
//
// TODO: 在此處添加建構函式邏輯
//
}
public void ProcessRequest(HttpContext Context)
{
try
{
//取得原始URL屏蔽掉參數
string Url = Context.Request.RawUrl;
//建立Regex
System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex
(@"/show-(\d+)-(\d+)\..+",System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//用Regex進行匹配
System.Text.RegularExpressions.Match m =
Reg.Match(Url,Url.LastIndexOf("/"));//從最後一個“/”開始匹配
if (m.Success)//匹配成功
{
String RealPath =
@"~/aspx/show.aspx?type=" + m.Groups[1] + "&id=" + m.Groups[2];
//Context.Response.Write(RealPath);
//Context.RewritePath(RealPath);//(RewritePath 用在無 Cookie 工作階段狀態中。)
Context.Server.Execute(RealPath);
}
else
{
Context.Response.Redirect(Context.Request.Url.ToString());
}
}
catch
{
Context.Response.Redirect(Context.Request.Url.ToString());
}
}
/// <summary>
/// 實現“IHttpHandler”介面所必須的成員
/// </summary>
/// <value></value>
/// Author:yoyo
/// blog:http://yangmingsheng.cn/
public bool IsReusable
{
get { return false; }
}
}
2.在web.config檔案還要添加一下設定項
在<system.web>節點下添加如下代碼:
程式碼<httpHandlers>
<add verb="*" path="*/show-?*-?*.aspx" type="UrlRewriter" />
</httpHandlers>
解釋一下:
verb是指允許的動作“GET”、“POST”、“PUT”中的一種或幾種,星號“*”表示全部允許;
path是指匹配路徑,支援簡單的萬用字元;
type是指綁定的類名以及包括命名空間(如果有的話);
對了,首先你要建立一個WEB表單“show.aspx”在目錄“aspx”下,因為這個檔案就是實際接受請求並顯示相關內容的頁面。
OK!,編譯,開啟網站輸入地址http://localhost/show-12-34.aspx 訪問一下,檢查看是不是顯示的“/aspx/show.aspx?type=12&id=34”的內容呢?!
上面我是設定了匹配ASPX檔案,因為IIS裡.HTML副檔名預設是不歸ASP.NET接管的,如果要接管HTML請求,
請將IIS的副檔名.HTML映射到“C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll”,
然後將上面的aspx改成html:
<httpHandlers>
<add verb="*" path="*/show-?*-?*.html" type="UrlRewriter" />
</httpHandlers>
現在開啟網站輸入地址http://localhost/show-12-34.html 訪問一下~!