.NET中關於僞靜態的實現方法

讓我們仔細看一下那些優秀網站的網址,我們會發現他們都是有一定的規則的,比如按產品分:http://www.abc.com/prod/1.html,按用戶分:http://www.abc.com/user/2.html, 這樣的網址看上去比較友好,至少比http://www.abc.com/user.aspx?id=3這樣要友好的多.那麼我們現在就可以思考一下,這是怎麼實現的.

  這裏要用到的關鍵技術是URL重寫技術,咋一聽,比較複雜,實際上,初次理解,也確實比較複雜.MS有一篇介紹這個原理的文章,大家可以看一下:http://www.microsoft.com/china/msdn/library/webservices/asp.net/URLRewriting.mspx?mfr=true

  最最簡單的實現,就是從上面的這個網址上下載MSDNURLRewriting.msi,安裝完成後,就生成了一個解決方案,裏面有實現的原代碼.通常情況下,這些原代碼可以不用改,直接使用.那麼我們共同看一下如果實現一個最簡單的重寫.

1.新建立一個web項目,添加剛纔下載下來生成的dll.

2.修改web.config,這比較重要,所有的重寫規則都要在這裏寫.

  示例:

在<configuration></configuration>中加入:

     <configSections>
          <section name="RewriterConfig"

type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
     </configSections>

     <RewriterConfig>
          <Rules>
              <RewriterRule>
                   <LookFor>~/(/d{4})/(/d{2})/Default/.aspx</LookFor>
                   <SendTo>~/Default.aspx?ID=$1</SendTo>
              </RewriterRule>
          </Rules>
     </RewriterConfig>

然後在<system.web></system.web>中加入:

<httpHandlers>
   <add verb="*" path="*.aspx"
        type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
</httpHandlers>

最後在地址欄上鍵入:http://localhost/Test/2004/12/News.aspx

效果出來了。

上面的<LookFor>~/(/d{4})/(/d{2})/News/.aspx</LookFor>這句這正則表達式URL,即被重寫的URL,而<SendTo>~/Default.aspx?ID=$1</SendTo>這一句爲原始URL地址。其中的$1爲第一個正則表達式值(上面例子爲:2004),以此類推,第二個即爲$2

簡單吧,這就是最簡單的應用了,不過這已經可以滿足了最常見的情況了.但是這種方法有一個弊端,那就是不能修改域名前面的部分,什麼意思呢??我們經常會看到一些網址是類似於這樣的,http://use1.abc.com,這可以理解爲一個用戶在這個網站上的網址,對於這種方式,上面的方法就不能實現了,這要用到兩種技術,泛域名解析+URL重寫.

什麼是泛域名解析,這個網上的解釋很多,我在這裏就不多說了.在做完泛域名解析後,就可以修改web.config裏面的內容了,

只需改成下面的樣子就可以了.

<configuration>
   
  <configSections>
  <section name="RewriterConfig"

type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
  </configSections>
  
  <RewriterConfig>
  <Rules>
  
  <RewriterRule>
  <LookFor>~/([a-zA-Z0-9]*)/.aspx</LookFor>
  <SendTo>~/List.aspx?Info=$1</SendTo>
  </RewriterRule>
  
  <RewriterRule>
  <LookFor>~/([a-zA-Z0-9]*)/.html</LookFor>
  <SendTo>~/List.aspx?Info=$1</SendTo>
  </RewriterRule>
  
  <RewriterRule>
  <LookFor>http://([a-zA-Z0-9]*)/.blog/.chp365/.cn/</LookFor>
  <SendTo>~/webuserblog/$1/default.htm</SendTo>
  </RewriterRule>
  
  </Rules>
  </RewriterConfig>
  <system.web>
  <httpModules>
  <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" />
  </httpModules>

另外,還要在IIS中,添加一個通配符應用程序映射,指到aspx的那個文件就可以了.

下面我引用一下網友KILLHAND的兩篇文章來說一下如何在實踐中運用.他的文章寫的很好.

UrlReWriter 使用經驗小結

#UrlRewriter 是微軟封裝好了的一個URL重寫組件。使用它可以讓我節約很多自已開發的時間。

好了,開始講述我的應用經驗,這只是很菜鳥的經驗,高手就不用看了。

第一步,請從此下載此組件。解壓,把UrlRewriter.dll copy到你的項目 bin 目錄下。

第二步,在Web.config中加入:

<?xml version="1.0" encoding="gb2312" ?>
<configuration>
     <configSections>
          <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
     </configSections>

第二步,加入重寫的規則節點:
如:  
   <RewriterConfig>
          <Rules>
              <RewriterRule>
                   <LookFor>~/Sell/(.[0-9]*)/.html</LookFor>
                   <SendTo>~/Search/Search_Sell.aspx?id=$1</SendTo>
              </RewriterRule>
              <RewriterRule>
                   <LookFor>~/Sell/Search_Sell/.aspx</LookFor>
                   <SendTo>~/Search/Search_Sell.aspx</SendTo>
              </RewriterRule>
              <RewriterRule>
       <LookFor>~/Buy/(.[0-9]*)/.html</LookFor>
                   <SendTo>~/Search/Search_Buy.aspx?id=$1</SendTo>
              </RewriterRule>
              <RewriterRule>
       <LookFor>~/Buys/(.[0-9]*)/.html</LookFor>
                   <SendTo>~/Buys/Show.aspx?id=$1</SendTo>
              </RewriterRule>
          </Rules>
     </RewriterConfig>

這個就要根據你的需要了,如果你對正則表達式不熟,那麼沒辦法,要麼憑藉你的高智商去找其中規律,稍稍改一下就能爲你所用了。呵呵。如果實在搞不清,那就自己GOOGLE一下正則表達式吧。(本人開始是參考別人的配置猜的,竟然用對了,呵呵。後來還是看了一下相關資料,發現這東東很有用。)

第三步,加入模塊配置(寫在<system.web>裏面):
如: 
 <httpHandlers>
     <add verb="*" path="*.aspx" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
  </httpHandlers>
(這裏表示使用HTTP程序來處理重寫)

好了,到了現在我們可以試一下看。

於是輸入:http://127.0.0.1:8080/Sell/1.aspx 出現了,呵呵。但是如果所它改爲:http://127.0.0.1:8080/Sell/1.html
暈,發現不行。汗。。。
呵呵,原因是沒把HTML的解析用 asp.net  的ISAPI來解析。
辦法是。。。

第四步,在IIS/你的站點/屬性/主目錄/配置/映謝 加入一個和 aspx 頁面的配置相同的擴展名項。注意“確認文件是否存在”不要勾選,否則會出現找不到文件。

現在再來試試看。什麼?#¥%#¥%#,還是不行。呵呵。不要急,咱們回過頭再來看看,原來在 web.config 中我們沒有配置 .html 也使用模塊此解析。

第五步,在模塊配置中加入:
  <httpHandlers>
     <add verb="*" path="*.aspx" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
     <add verb="*" path="*.html" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
  </httpHandlers>

現在總可以了吧,呵呵。終於看到了,興奮吧。不要急,這還只是最簡單的。如果你的頁面有回傳。比如說放了DATAGRID,有分頁的,你點到下一頁就發現,暈倒,又出問題了。
這下怎麼辦呢,這個其實微軟件的網站上就有說到,我在這裏簡述一下了。


第六步,加入窗體回傳保持的組件:
在原來你下載的項目裏找到 ActionlessForm.dll 放到你的項目 bin 目錄下。

然後在你的這個頁面中加入:
<%@ Register TagPrefix="skm" Namespace="ActionlessForm" Assembly="ActionlessForm" %>
再把你的<Form...>改爲:
<skm:Form id="你的表單名" method="post" runat="server">
.....
</skm:Form>

That's All.現在你可以高枕無憂了。一切如你所願。

最後,恭祝各位一切順利。

利用UrlRewriter 實現二級域名

從上一篇文章,我們可以實現對域名後面的那部分進行重寫,那麼可不可以對前面那部分進行重寫而實現二級域名呢?
答案是肯定的。

這樣,首先我們得修改UrlRewriter,怎麼修改請參見江大魚的BLog

1.BaseModuleRewriter.cs

protected virtual void BaseModuleRewriter_AuthorizeRequest(object sender, EventArgs e)
        
{
            HttpApplication app 
= (HttpApplication) sender;
            Rewrite(app.Request.Path, app);
        }


改爲

protected virtual void BaseModuleRewriter_AuthorizeRequest(object sender, EventArgs e)
        
{
            HttpApplication app 
= (HttpApplication) sender;
            Rewrite(app.Request.Url.AbsoluteUri, app);
        }



就是將  app.Request.Path 替換成了  app.Request.Url.AbsoluteUri

2.ModuleRewriter.cs

for(int i = 0; i < rules.Count; i++)
            
{
                
// get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
                string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$";

                
// Create a regex (note that IgnoreCase is set)
                Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);

                
// See if a match is found
                if (re.IsMatch(requestedPath))
                
{
                    
// match found - do any replacement needed
                    string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].SendTo));

                    
// log rewriting information to the Trace object
                    app.Context.Trace.Write("ModuleRewriter""Rewriting URL to " + sendToUrl);

                    
// Rewrite the URL
                    RewriterUtils.RewriteUrl(app.Context, sendToUrl);
                    
break;        // exit the for loop
                }

            }


改爲

for(int i = 0; i < rules.Count; i++)
            
{
                
// get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
                string lookFor = "^" + rules[i].LookFor + "$";

                
// Create a regex (note that IgnoreCase is set)
                Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);

                
// See if a match is found
                if (re.IsMatch(requestedPath))
                
{
                    
// match found - do any replacement needed
                    string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].SendTo));

                    
// log rewriting information to the Trace object
                    app.Context.Trace.Write("ModuleRewriter""Rewriting URL to " + sendToUrl);

                    
// Rewrite the URL
                    RewriterUtils.RewriteUrl(app.Context, sendToUrl);
                    
break;        // exit the for loop
                }

            }




string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$";

改成了

string lookFor = "^" + rules[i].LookFor + "$";


完成這2處改動之後重新編譯項目,將生成的dll複製到bin目錄下。

修改完了這後,我們再把此 UrlRewriter.dll COPY 到我們項目的Bin目錄下。這樣就結了麼?沒有。
首先請確定你的項目之前有按我上篇文章中寫到的那樣做過UrlRewriter的配置,否則請先回過頭來看看那篇文章。

如果你的項目已配置過,那麼,我們還要爲此做以下幾件事情:

1。請確定你的域名是支持泛解析的。然後你的網站爲默認網站,否則將不能實現(至少我現在還沒有找到好辦法)
2。在IIS配置:在IIS/你的站點/屬性/主目錄/配置/映謝 在通配符應用程序配置處插入一個新的映謝。把可執行文件設爲和上面ASPX頁面同樣的配置即可(注意不要勾選 “確定文件是否存在”)。(用處就是使所有請求通過 asp.net 的ISAPI來處理,只有這樣才能對所有地址進行重寫嘛。)
3。查看下你的網站主機頭,裏面的第一個主機頭值必須爲空,否則會出現錯誤的請求。後面就隨你加了,看你想綁定多少域名了。(這個辦法是江大魚想出來的。爲這個錯誤我們都想了好多辦法。在這裏感謝江大魚。。。)
4。最後改寫你的 web.config 文件。
把上節中說到的
  <httpHandlers>
     <add verb="*" path="*.aspx" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
     <add verb="*" path="*.html" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
  </httpHandlers>
改爲:
  <httpModules>
   <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" />
  </httpModules>
(就是改用HTTP 模塊來執行重寫,而不用HTTP 程序,否則無法重寫地址前面。)
然後就來修改我們的重寫正則了:
              <RewriterRule>
                   <LookFor>http://(.[0-9]*)/.178b2b/.com/</LookFor>
                   <SendTo>~/Search/Search_Sell.aspx?id=$1</SendTo>
              </RewriterRule>
好了,現在你輸入 http://1.178b2b.com/ 就能搜索出相應分類了。但是聰明的你馬上就發現。暈死,首頁進不去了。呵呵。當然嘍。你還得爲首頁加入重寫正則。
              <RewriterRule>
                   <LookFor>http://www/.178b2b/.com/</LookFor>
                   <SendTo>~/index.htm</SendTo>
              </RewriterRule>

大功告成。感覺爽死了吧。呵呵。莫急,如果你二級域名指向的目錄下面的頁面都用的相對地址連接的圖片和其它頁面的話,呵呵,你有得忙了,你要全部改成如下方式:
<a href=http://www.178b2b.com/cxlm/league.html target="_blank">誠信聯盟</a>

以上就是用UrlRewriter實現二級域名的方法了。希望各位一切順利。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章