国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

UrlRewrite(URL重寫)--ASP.NET中的實現

2019-11-17 02:12:03
字體:
來源:轉載
供稿:網友

UrlRewrite(URL重寫)--asp.net中的實現

2015-07-15 23:25 by Mike.Jiang, ... 閱讀, ... 評論, 收藏, 編輯

概述

今天看了下URL重寫的實現,主要看的是MS 的URL Rewrite。

URL重寫的優點有:更友好的URL,支持老版本的URL

URL重寫的缺點有:最主要的缺點是性能低下,因為如果要支持無后綴的URL(但更多的情況是我們要支持這種方式)就必須在IIS中配置所有的URL(包括js,CSS,image)都要轉發到aspnet_isapi中,解決方法可以參見 慎用url重寫;還有一個性能問題是,根據源代碼,在匹配url時,用正則表達式嘗試匹配每一個規則,直至有一個匹配成功,或都匹配不成功才結束。那么那些不需要重寫的URL,就要將所有的正則表達式都要執行一次,可以在進入匹配之前先做一個判斷,排除掉一些情況

1 配置 web.config

1.1 下載 MS的URLRewrite

地址是:http://download.microsoft.com/download/0/4/6/0463611e-a3f9-490d-a08c-877a83b797cf/MSDNURLRewriting.msi

1.2 配置自定義section的聲明節點

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

1.3 配置自定義section的內容

用UrlRewrite在完成配置后,主要的工作就是寫配置url映射的正則表達式了。對于正則式不清楚的人,可以看看這個正則表達式入門及備忘

  <RewriterConfig>    <Rules>      <RewriterRule>        <LookFor>~/pick/?</LookFor>        <SendTo><![CDATA[~/pick.aspx]]></SendTo>      </RewriterRule>      <RewriterRule>        <LookFor>~/pick/(/d+)</LookFor>        <SendTo><![CDATA[~/pick.aspx?page=$1]]></SendTo>      </RewriterRule>      <RewriterRule>        <LookFor>~/(/w+)/p/(/d+).html</LookFor>        <SendTo><![CDATA[~/BlogDetails.aspx?blogwriter=$1&blogid=$2]]></SendTo>      </RewriterRule>      <RewriterRule>        <LookFor>~/PRoduct/(/w{4}).html</LookFor>        <SendTo>~/Product.aspx?id=$1</SendTo>      </RewriterRule>    </Rules>  </RewriterConfig>

1.4 配置httpmodules或httphandlers

在如果是舊的IIS 6.0,在<system.web>節點下配置,httpmodules和httphandlers只需要一個就好,用于攔截所有請求

    <httpModules>        <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" />    </httpModules>        <!--<httpHandlers>        <add verb="*" path="*.aspx" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />    </httpHandlers>-->

在新的IIS7.0中, 在<system.webServer>節點下配置, modules 和handlers同樣只需要一個

  <system.webServer>    <modules>      <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" />    </modules>    <!--<handlers>      <add verb="*" path="*.*" type="URLRewriter.RewriterFactoryHandler, URLRewriter" name="URLRewriter" />    </handlers>-->  </system.webServer>

1.5 配置IIS

在發布到IIS后,如果訪問路徑出錯,需要做一下擴展名的映射。額,我用的IIS7.0是沒有報錯,直接就可訪問了。

2 代碼分析

UrlRewrite的源代碼十分的簡單,實際上就是實現了一個IHttpModule的接口來攔截所有的請求URL。然后,將請求的URL用正則表達式與每一個匹配,直到有一個匹配成功,則將原有的url(假的)根據正則表達式轉成實際的url。如果都匹配不成功,則按原有的路徑處理請求

主要代碼是

protected override void Rewrite(string requestedPath, System.Web.Httpapplication app)        {            // log information to the Trace object.            app.Context.Trace.Write("ModuleRewriter", "Entering ModuleRewriter");            // get the configuration rules            RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;            // iterate through each rule...            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                }            }            // Log information to the Trace object            app.Context.Trace.Write("ModuleRewriter", "Exiting ModuleRewriter");        }
View Code

看了這個源代碼,還學到的一個東西就是在web.config中自定義節點,然后實現一下IConfigurationSectionHandler 接口,將section的內容轉成對象,在程序中使用,主要代碼有:

        public static RewriterConfiguration GetConfig()        {            if (HttpContext.Current.Cache["RewriterConfig"] == null)                HttpContext.Current.Cache.Insert("RewriterConfig", ConfigurationManager.GetSection("RewriterConfig"));                        return (RewriterConfiguration) HttpContext.Current.Cache["RewriterConfig"];        }    /// <summary>    /// Deserializes the markup in Web.config into an instance of the <see cref="RewriterConfiguration"/> class.    /// </summary>    public class RewriterConfigSerializerSectionHandler : IConfigurationSectionHandler     {        /// <summary>        /// Creates an instance of the <see cref="RewriterConfiguration"/> class. : IConfigurationSectionHandler         /// </summary>        /// <remarks>Uses xml Serialization to deserialize the XML in the Web.config file into an        /// <see cref="RewriterConfiguration"/> instance.</remarks>        /// <returns>An instance of the <see cref="RewriterConfiguration"/> class.</returns>        public object Create(object parent, object configContext, System.Xml.XmlNode section)         {            // Create an instance of XmlSerializer based on the RewriterConfiguration type...            XmlSerializer ser = new XmlSerializer(typeof(RewriterConfiguration));            // Return the Deserialized object from the Web.config XML            return ser.Deserialize(new XmlNodeReader(section));        }    }
View Code

3 最后

最后就是,UrlReWrite雖然好用,但是根據這源代碼,性能問題是個大頭,但平常自己的小網站用用還是沒問題的,如果請求量大了,也知道這里UrlRewrite這里有問題,可以用httphander的方式只攔截特定的url,也可以用IIS filter去搞(沒搞過,但應該能用,畢竟是在IIS端攔截大部分的請求,而不是將求放到擴展程序中去)。關于IIS filter可以參考這個文章 在 ASP.NET 中執行 URL 重寫


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 岳池县| 吉水县| 新邵县| 祁门县| 察隅县| 成都市| 渭南市| 定兴县| 上饶县| 龙州县| 江孜县| 江门市| 漳浦县| 石家庄市| 浙江省| 嘉禾县| 阜阳市| 曲水县| 高唐县| 登封市| 华蓥市| 化隆| 延吉市| 杂多县| 昔阳县| 郓城县| 台北县| 蒙城县| 郴州市| 贡觉县| 渑池县| 象山县| 乌鲁木齐市| 铜鼓县| 尖扎县| 于田县| 涞水县| 黄龙县| 炉霍县| 夹江县| 南川市|