Asp.net實現URL重寫

【概述】html

URL重寫就是首先得到一個進入的URL請求而後把它從新寫成網站能夠處理的另外一個URL的過程。重寫URL是很是有用的一個功能,由於它可讓你提升搜索引擎閱讀和索引你的網站的能力;並且在你改變了本身的網站結構後,無須要求用戶修改他們的書籤,無需其餘網站修改它們的友情連接;它還能夠提升你的網站的安全性;並且一般會讓你的網站更加便於使用和更專業。web

【過程】

 
【方法】
一、在asp.net請求管道中重寫路徑
二、經過組件,如微軟的UrlRewriter.dll
 
【介紹】
一、在asp.net請求管道中重寫路徑
要重寫,首先是截獲客戶端請求的URL,而後分析當時的URL,最後跳轉到相應的頁面。這裏經過自定義HttpModule來截獲URL請求,並經過正則來實現URL的解析,而後轉換成網站能識別的路徑。
a) 在解決方案中先添加一個【類庫】項目:UrlReWriter,在項目中添加類:MyUrlWriter,該類繼承IHttpModule接口,代碼以下:
 1      class MyUrlWriter : IHttpModule
 2       {
 3             public void Init( HttpApplication context)
 4             {
 5                   context.BeginRequest += new EventHandler (context_BeginRequest);
 6             }
 7  
 8             protected void context_BeginRequest( object sender, EventArgs e)
 9             {
10                   HttpApplication application = sender as HttpApplication ;
11                   HttpContext context = application.Context; //上下文
12                   string url = context.Request.Url.LocalPath; //得到請求URL
13  
14                   Regex articleRegex = new Regex ("/Article/[A-Z0-9a-z_]+" ); //定義規則
15                   if (articleRegex.IsMatch(url))
16                   {
17                         string paramStr = url.Substring(url.LastIndexOf('/' ) + 1);
18                         context.RewritePath( "/Article.aspx?id=" + paramStr);
19                   }
20                   else
21                   {
22                         context.RewritePath( "/Default.aspx" );
23                   }
24             }
25  
26             public void Dispose() { }
27       }
b) 在解決方案中添加一個網站項目,在引用中添加UrlReWriter的項目引用,而後在web.config中將自定義的HttpModule註冊進去,代碼以下:
1   <httpModules >
2         <add name = "UrlReWriter " type =" UrlReWriter.MyUrlWriter,UrlReWriter " />
3    </httpModules >
c) 而後添加一個Article.aspx頁面,在Article.aspx.cs類中添加輸出語句,代碼以下:
1       public partial class Article : System.Web.UI.Page
2       {
3             protected void Page_Load( object sender, EventArgs e)
4             {
5                   Response.Write(Request.QueryString[ "id" ]);
6             }
7       }
d) 最後在Default.aspx頁面中添加測試連接,代碼以下:
1 <a href ="/Article/35">測試url重寫</a>
e) 項目截圖以下:
f) 按【F5】運行,打開Default.aspx頁,以下:
g) 點擊後轉到Article.aspx頁面,實現重寫,以下:
二、經過組件,如微軟的UrlRewriter.dll
這個組件的原理和咱們自定義HttpModule的原理同樣,也是進入管道後攔截BeginRequest請求,而後將配置文件中的路徑規則(正則表達式)引用過來,而後對請求的路徑按正則進行替換成網站識別的路徑。這個組件的核心代碼(未翻譯)以下:
      
 1     /// <summary>
 2       /// Provides a rewriting HttpModule.
 3       /// </summary>
 4       public class ModuleRewriter : BaseModuleRewriter
 5       {
 6             /// <summary>
 7             /// This method is called during the module's BeginRequest event.
 8             /// </summary>
 9             /// <param name="requestedRawUrl"> The RawUrl being requested (includes path and querystring).</param>
10             /// <param name="app"> The HttpApplication instance. </param>
11             protected override void Rewrite( string requestedPath, System.Web.HttpApplication app)
12             {
13                    // log information to the Trace object.
14                   app.Context.Trace.Write( "ModuleRewriter" , "Entering ModuleRewriter");
15  
16                    // get the configuration rules
17                   RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;
18  
19                    // iterate through each rule...
20                   for (int i = 0; i < rules.Count; i++)
21                   {
22                          // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
23                         string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$" ;
24  
25                          // Create a regex (note that IgnoreCase is set...)
26                         Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
27  
28                          // See if a match is found
29                         if (re.IsMatch(requestedPath))
30                         {
31                                // match found - do any replacement needed
32                               string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath,re.Replace(requestedPath, rules[i].SendTo));
33  
34                                // log rewriting information to the Trace object
35                               app.Context.Trace.Write( "ModuleRewriter" , "Rewriting URL to " + sendToUrl);
36  
37                                // Rewrite the URL
38                               RewriterUtils.RewriteUrl(app.Context, sendToUrl);
39                               break ;             // exit the for loop
40                         }
41                   }
42  
43                    // Log information to the Trace object
44                   app.Context.Trace.Write( "ModuleRewriter" , "Exiting ModuleRewriter");
45             }
46       }
a) 先想辦法獲得一個UrlRewriter.dll,經過http://download.microsoft.com/download/0/4/6/0463611e-a3f9-490d-a08c-877a83b797cf/MSDNURLRewriting.msi下載。下載獲得的是一個用vs2003開發的源文件,能夠用vs2008或者更高版本編譯器轉換後,生成解決方案,在bin目錄中生成UrlRewriter.dll文件。
b) 新建一個網站項目,添加引用第一步產生的UrlRewriter.dll文件,添加Article.aspx、News.aspx頁面。
c) 在Article.aspx後臺代碼中添加一行輸出方法,代碼以下:
1       public partial class Article : System.Web.UI.Page
2       {
3             protected void Page_Load( object sender, EventArgs e)
4             {
5                   Response.Write(Request.QueryString[ "id" ]);
6             }
7       }
d) 在News.aspx後臺代碼中添加一行輸出方法,代碼以下:
      public partial class News : System.Web.UI.Page
      {
            protected void Page_Load( object sender, EventArgs e)
            {
                  Response.Write( string .Format("日期:{0}<br/>" , Request.QueryString["date" ]));
                  Response.Write( string .Format("ID:{0}<br/>" , Request.QueryString["id" ]));
            }
      }
e) 打開web.config文件,在節點<configSections>中添加一個<section>節點,代碼以下:
1     <configuration>
2       <configSections>
3         <section name = "RewriterConfig " type =" URLRewriter.Config.RewriterConfigSerializerSectionHandler,URLRewriter " />
4       </configSections>
5     </configuration>
f) 在<httpHandlers>節點中加入後綴斷定規則,代碼以下:
1     <httpHandlers>
2       <remove verb = "* " path = "*.asmx " />
3       <add verb = "* " path = "* " type = "URLRewriter.RewriterFactoryHandler, URLRewriter" />
4       <add verb = "* " path = "*.html " type =" URLRewriter.RewriterFactoryHandler, URLRewriter " />
5     </httpHandlers>
g) 在節點中配置URL規則,代碼以下:
 1     <configuration>
 2        <RewriterConfig>
 3          <Rules>
 4                 <RewriterRule>
 5                        <LookFor>~/Article/([A-Z0-9a-z_]+) </LookFor>
 6                        <SendTo>~/Article.aspx?id=$1 </SendTo>
 7                 < RewriterRule>
 8                 <RewriterRule>
 9                        <LookFor>~/News/(\d{4}-\d{2}-\d{2})/(\d{1,6})\.html? </LookFor>
10                        <SendTo>~/News.aspx?date=$1 &amp; id=$2</SendTo>
11                 </RewriterRule>
12          </Rules>
13        </RewriterConfig>
14   </configuration>
LooFor節點表示與請求URL匹配的路徑正則,SendTo表示轉換後的地址規則,$1表示LookFor正則中第一個括號匹配獲得的值,$2表示LookFor正則中第二個括號匹配獲得的值,熟悉正則的朋友都知道這個。
h) 最後在Default.aspx頁面中添加兩個測試連接,代碼以下:
1         <a href ="<% = ResolveUrl("Article/35")%> "> 測試文章url重寫</a>< br />
2         <a href ="<% = ResolveUrl("News/2014-06-11/285864.html")%> "> 測試新聞url重寫</a>
i) 按【F5】運行,打開Default.aspx頁,以下:
j) 點擊「測試文章url重寫」,以下:
k) 點擊「測試新聞url重寫」,以下:
 
【總結】
這個知識點很簡單,不少大牛們也寫過,這篇文章也參考了幾位高手的博客,而後本身寫了兩個demo。
有些東西,你能寫出來和表述出來才能說你會了。
但願對你們有幫助,謝謝支持。
相關文章
相關標籤/搜索