2、修改web.config的內容。
代碼如下:
<system.web>
<httpHandlers>
<add verb="*" path="*.zhtml" type="ZDIL.URLRewriter.RewriterFactoryHandler, ZDILURLRewriter" />
</httpHandlers>
</system.web>
其中*.zhtml 就是地址欄里面寫的網頁的擴展名,就是給用戶看的,這個可以隨意改(但是要符合擴展名的規則!)。當然要和第一步里面的設置相一致才行。
3、寫一個類。代碼
代碼如下:
using System;
using System.IO;
using System.Web;
using System.Web.UI;
namespace ZDIL.URLRewriter
{
/**//// <summary>
/// URL重寫
/// </summary>
public class RewriterFactoryHandler : IHttpHandlerFactory
{
/**//// <summary>
/// GetHandler is executed by the ASP.NET pipeline after the associated HttpModules have run. The job of
/// GetHandler is to return an instance of an HttpHandler that can process the page.
/// </summary>
/// <param name="context">The HttpContext for this request.</param>
/// <param name="requestType">The HTTP data transfer method (<b>GET</b> or <b>POST</b>)</param>
/// <param name="url">The RawUrl of the requested resource.</param>
/// <param name="pathTranslated">The physical path to the requested resource.</param>
/// <returns>An instance that implements IHttpHandler; specifically, an HttpHandler instance returned
/// by the <b>PageParser</b> class, which is the same class that the default ASP.NET PageHandlerFactory delegates
/// to.</returns>
public virtual IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
string sendToUrl = url; //地址欄里面的地址
string filePath = pathTranslated;
string sendToURLString = "/web/index.aspx"; //真正要訪問的頁面
string queryString = ""; //參數。比如 ?id=123
filePath = context.Server.MapPath(sendToURLString); //物理地址
//這句最重要了。轉向了。
context.RewritePath(sendToURLString, String.Empty, queryString);
return PageParser.GetCompiledPageInstance(url, filePath, context);
}
public virtual void ReleaseHandler(IHttpHandler handler)
{
}
}
}
這個類呢,要寫在一個單獨的項目里面,然后編譯成 ZDILURLRewriter.DLL文件。(注意文件名,寫錯了就不能正常運行了)。
4、完成了。
打開IE ,在地址欄里輸入 http://.../1.zhtml。
瀏覽者看到是一個靜態頁的地址,但是實際上訪問的卻是 /web/index.aspx 這個動態網頁。
怎么樣簡單吧。
當然了,這個是最簡單的,簡單到了“不能用”的地步了。因為他會把所有的 *.zhtml 的訪問都“重寫”到 /web/index.aspx 。
至于把什么樣的網頁重寫到哪個網頁,這里就不介紹了(這里只講方法,不講實現的細節)。
方法很多了,原作是通過正則來匹配的,我是通過 string sendToUrl = url; 來判斷的。
其他的就看你們的需要了。聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com