在外界看來,網站上有三個單獨的網頁(對搜索爬蟲而言,這看上去很棒)。通過使用 HttpContext的RewritePath方法,我們可以在這些請求剛進入服務器時,動態地把收到的URL重寫成單個Products.aspx網頁接受一個查詢字符串的類別名稱或者PathInfo參數。譬如,我們可以使用Global.asax中的 Application_BeginRequest事件,來這么做:
void Application_BeginRequest(object sender, EventArgs e) { string fullOrigionalpath = Request.Url.ToString(); if (fullOrigionalpath.Contains("/Products/Books.aspx")) { Context.RewritePath("/Products.aspx?Category=Books"); } else if (fullOrigionalpath.Contains("/Products/DVDs.aspx")) { Context.RewritePath("/Products.aspx?Category=DVDs"); } }
手工編寫象上面這樣的編碼的壞處是,很枯燥乏味,而且容易犯錯。我建議你別自己寫,而是使用網上現成的HttpModule來完成這項工作。這有幾個你現在就可以下載和使用的免費的HttpModule:
* UrlRewriter.net
* UrlRewriting.net
這些模塊允許你用聲明的方式在你應用的web.config文件里表達匹配規則。譬如,在你應用的web.config文件里使用UrlRewriter.Net模塊來把上面的那些URL映射到單個Products.aspx頁上,我們只要把這個web.config文件添加到我們的應用里去就可以了(不用任何編碼):
<?xml version="1.0"?> <configuration> <configSections> <section name="rewriter" requirePermission="false" type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" /> </configSections> <system.web> <httpModules> <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter"/> </httpModules> </system.web> <rewriter> <rewrite url="~/products/books.aspx" to="~/products.aspx?category=books" /> <rewrite url="~/products/CDs.aspx" to="~/products.aspx?category=CDs" /> <rewrite url="~/products/DVDs.aspx" to="~/products.aspx?category=DVDs" /> </rewriter> </configuration>
上面的HttpModule URL重寫模塊還支持正則表達式和URL模式匹配(以避免你在web.config 文件里硬寫每個URL)。所以,不用寫死類別名稱,你可以象下面這樣重寫匹配規則,把類別名稱動態地從任何/products/[類別].aspx組合的 URL里取出來:
<rewriter> <rewrite url="~/products/(.+).aspx" to="~/products.aspx?category=$1" /> </rewriter>