ASP.NET的URL Rewrite組件
可能已經沒有人會使用上一篇ASP.NET文章中的方法進行URL Rewrite了,因為提供URL Rewrite組件早已鋪天蓋地了。
ASP.NET級別的URL Rewrite組件的原理很簡單,其實只是監聽BeginRequest事件,并且根據配置來決定目標URL。在我之前接觸過的項目中,發現使用URLRewriter作為URL Rewrite組件的頻率非常高,我想可能是因為那是微軟提供的東西吧。
如果要使用URLRewriter,首先自然就是在web.config中配置一個HttpModule:
- <httpModules>
- <add name="ModuleRewriter" type="URLRewriter.ModuleRewriter, URLRewriter" />
- </httpModules>
然后就是進行配置了(注:強烈建議使用configPath屬性將配置提取成額外的文件,便于管理):
- <configSections>
- <section name="RewriterConfig"
- type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
- </configSections>
- <RewriterConfig>
- <Rules>
- <RewriterRule>
- <LookFor>~/tag/([\w]+)/</LookFor>
- <SendTo>~/Tags.aspx?Tag=$1</SendTo>
- </RewriterRule>
- </Rules>
- </RewriterConfig>
正則表達式是一個非常了不得的東西,能匹配,能捕獲。在上面的例子中,我們把符合LookFor條件的“/tag/xxx”重新定位到 Tags.aspx頁面上,并且將xxx作為Tag這個QueryString項的值,這樣就能夠在代碼中通過 HttpContext.Request.QueryString["Tag"]來獲得該值了。
URL Rewriter的功能對于大多數應用來說已經足夠了,但是我總是不喜歡。但如果非要問我不喜歡的原因,我也難說出個子丑寅卯來。可能僅僅是這個配置方式的問題吧。在使用 URL Rewriter時,配置段往往會非常長,每個配置項需要從<RewriterRule>到</RewriterRule>共4 行代碼,一個規模不大的項目都很容易出現上百行的配置。“這也太XML了”,我想,為什么不用XML Attribute呢?這樣每個配置項就能縮短為1行了——不過,這是ASP.NET題外話。
所以如果我目前要做URL Rewrite,往往用的是Intelligencia出品的開源組件Url Rewriter.NET。雖然這個名字和前一個非常相似,但是功能卻遠超前者。該組件在使用上和URL Rewriter比較接近(其實似乎所有的URL Rewrite組件都差不多),我們要做的也只是配置:
- <configSections>
- <section name="rewriter"
- type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler,
- Intelligencia.UrlRewriter" />
- </configSections>
- <rewriter>
- <rewrite url="^/User/(\d+)$" to="~/User.aspx?id=$1" processing="stop" />
- <rewrite url="^/User/(\w+)$" to="~/User.aspx?name=$1" processing="stop" />
- </rewriter>
- <system.web>
- <httpModules>
- <add name="UrlRewriter"
- type="Intelligencia.UrlRewriter.RewriterHttpModule,
- Intelligencia.UrlRewriter" />
- </httpModules>
- </system.web>
【編輯推薦】