asp.net URL重寫簡化版 速學URL重寫

來源:互聯網
上載者:User

在 asp.net 裡實現 URL重寫(URLRewriter)的一個最簡單的方法。
參考了 (作者 Scott Mitchell 翻譯:Janssen )的大作,雖然沒有完全看明白,但是也照貓畫虎地做了一個,頗有“成就”感。寫出來分享一下。
原作裡講了很多的原理,這裡就不說了(其實我也不懂)。這裡就寫操作過程吧。目的是實現一個最簡單的能實現 URL重寫 的程式。
1、需要設定一下IIS裡的網站屬性。

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; 來判斷的。
其他的就看你們的需要了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.