url重寫就是把一些類似article.aspx?id=28的路徑
重寫成 article/28/這樣的路徑
當使用者訪問article/28/的時候
我們通過asp.net把這個請求重新導向到article.aspx?id=28路徑
有兩種方法可以做這件事情
一:基於HttpModule的方案
這個方案有有缺點,具體缺點以後再談
我曾寫過一篇文章《不用組件的url重寫(適用於較大型項目) 》
就是按這個模式寫的
二:基於HttpHandler的方案
我們這個例子就是按這個方案做的
我們接下來就按這種方式做這個例子
三:基於HttpHandlerFactory的方案
顧名思義這是一個工廠,可以根據不同的檔案來處理請求
先看webconfig,和上一節講的webconfig一樣
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true"></compilation>
<httpHandlers>
<add verb="*" path="*.jsp" type="xland.MyHandler" />
</httpHandlers>
</system.web>
</configuration>
verb是指允許的動作“GET”、“POST”、“PUT”中的一種或幾種,星號“*”表示全部允許
path允許訪問jsp副檔名的檔案
type指定HttpHandler處理方法
下面看MyHandler方法
using System;
using System.Collections.Generic;
using System.Web;//引用web命名空間
using System.Text;
namespace xland
{
public class MyHandler:IHttpHandler//繼承IHttpHandler
{
public void ProcessRequest(HttpContext context)//實現介面方法
{
string path = context.Request.Url.PathAndQuery;
int startnum = path.LastIndexOf('/') + 1;
string name = path.Substring(startnum);
string[] parames = name.Split('-');
string truename = "/"+parames[0]+".aspx"+"?id="+parames[1].Replace(".jsp","");
context.Server.Execute(truename);
}
public bool IsReusable//實現介面方法
{
get { return false; }
}
}
}
我的意圖就是把article-49.jsp這樣的使用者請求
轉換成article.aspx?id=49這樣的請求
最後一句是執行指定的頁面處理常式
下面看article.aspx
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace _1
{
public partial class article : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("接收到的id為" + Request["id"]);
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("回傳成功");
}
}
}
我在頁面裡做了按鈕的postback事件,在這裡是可以成功執行的
<httpHandlers>
<add verb="*" path="*.jsp" type="xland.MyHandler" />
</httpHandlers>
上面的代碼是處理所有的.jsp副檔名的檔案
你可以寫成
<httpHandlers>
<add verb="*" path="*123.jsp" type="System.Web.UI.PageHandlerFactory" validate="true" />
<add verb="*" path="*.jsp" type="xland.MyHandler" />
</httpHandlers>
把一類檔案交還給asp.net處理
然後通過註冊IhttpHandlerFactory處理你想處理的那部分