本文實(shí)例總結(jié)了ASP.NET實(shí)現(xiàn)偽靜態(tài)網(wǎng)頁(yè)方法,之用。具體方法如下:
方法一:利用Httphandler實(shí)現(xiàn)URL重寫(xiě)(偽URL及偽靜態(tài))
我們有時(shí)候會(huì)見(jiàn)到這樣的地址:“http://www.XXXX.com/show-12-34.html”,你或許認(rèn)為在站點(diǎn)服務(wù)器根目錄“/”下存在名為“show-12-34.html”的文件,其實(shí)實(shí)際它可能是不存在的,而可能你看到的內(nèi)容是“/aspx/show.aspx?type= 12&id=34”的內(nèi)容,為什么要這樣做呢?原因有多個(gè)方面:首先是增強(qiáng)URL的友好性,記“show-12-34.html”總比 “/aspx/show.aspx?type=12&id=34”好記吧?其次就是方便搜索引擎收錄,很多搜索引擎更看好靜態(tài)HTML頁(yè),比如:百度;其次就是出于安全性的考慮,因?yàn)檫@樣隱藏了參數(shù)“type”、“id”。是不是很有意思呢?
其實(shí)這是利用URL重寫(xiě)實(shí)現(xiàn)的,下面我就說(shuō)一下在ASP.NET2.0下我所知道的最簡(jiǎn)單的實(shí)現(xiàn)方法:通過(guò)實(shí)現(xiàn)接口“IHttpHandler”來(lái)接管HTTP請(qǐng)求,F(xiàn)ollow me!
1.在資源管理方案中添加一個(gè)類(lèi),類(lèi)的代碼如下:
//類(lèi)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重寫(xiě)類(lèi) /// Author:yoyo /// </summary> public class UrlRewriter : IHttpHandler //實(shí)現(xiàn)“IHttpHandler”接口 { public UrlRewriter() { // // TODO: 在此處添加構(gòu)造函數(shù)邏輯 // } public void ProcessRequest(HttpContext Context) { try { //取得原始URL屏蔽掉參數(shù) string Url = Context.Request.RawUrl; //建立正則表達(dá)式 System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex (@"/show-(/d+)-(/d+)/..+",System.Text.RegularExpressions.RegexOptions.IgnoreCase); //用正則表達(dá)式進(jìn)行匹配 System.Text.RegularExpressions.Match m = Reg.Match(Url,Url.LastIndexOf("/"));//從最后一個(gè)“/”開(kāi)始匹配 if (m.Success)//匹配成功 { String RealPath = @"~/aspx/show.aspx?type=" + m.Groups[1] + "&id=" + m.Groups[2]; //Context.Response.Write(RealPath); //Context.RewritePath(RealPath);//(RewritePath 用在無(wú) Cookie 會(huì)話狀態(tài)中。) Context.Server.Execute(RealPath); } else { Context.Response.Redirect(Context.Request.Url.ToString()); } } catch { Context.Response.Redirect(Context.Request.Url.ToString()); } } /// <summary> /// 實(shí)現(xiàn)“IHttpHandler”接口所必須的成員 /// </summary> /// <value></value> /// Author:yoyo public bool IsReusable { get { return false; } }}2.在web.config文件還要添加以下設(shè)置項(xiàng)
在<system.web>節(jié)點(diǎn)下添加如下代碼:
<httpHandlers>
<add verb="*" path="*/show-?*-?*.aspx" type="UrlRewriter" />
新聞熱點(diǎn)
疑難解答
圖片精選