Urlrewrite 配置信息写在另外的文件

由于伪静态的配置 太多,如果放在web.cofig里面可阅读性不强,而且频繁修改webconfig容易出错。

1.修改RewriterConfigSerializerSectionHandler类

using System;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;

namespace Utility.URLRewriter
{
    /// <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.
        /// </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) 
        {
            string sourcePath = section.Attributes["ConfigSource"].Value;

            // Create an instance of XmlSerializer based on the RewriterConfiguration type...
            XmlSerializer ser = new XmlSerializer(typeof(RewriterConfiguration));

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(System.Web.HttpContext.Current.Server.MapPath(sourcePath));
            // Return the Deserialized object from the Web.config XML
            return ser.Deserialize(new XmlNodeReader(xmlDoc));



            //// 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));
        }

    }
}

2.修改web.config

<configSections>
    <section name="RewriterConfig" type="URLRewriter.Config.CustomRewriterConfigSerializerSectionHandler, URLRewriter" />
</configSections>
<RewriterConfig ConfigSource="/config/URLRewriter.config"></RewriterConfig>

3.添加urlRewriter.config配置文件

<?xml version="1.0"?>
  <RewriterConfig>
    <Rules>
      <!-- Rules for Blog Content Displayer -->
      <RewriterRule>
        <LookFor>~/1.aspx</LookFor>
        <SendTo>~/Default.aspx</SendTo>
      </RewriterRule>
      <RewriterRule>
        <LookFor>~/(d{4})/(d{2})/(d{2}).aspx</LookFor>
        <SendTo>~/ShowBlogContent.aspx?year=$1&month=$2&day=$3</SendTo>
      </RewriterRule>
    </Rules>
  </RewriterConfig>

完成。

1.注意事项

因为公司的配置文件/config/URLRewriter.config修改的频率蛮高的,但也不是经常修改,但是在系统后台将此配置文件修改了之后配置信息不能立即生效,过了一些时间后才生效,除非重启IIS或者上传bin覆盖原有文件。

后来,发现配置伪静态信息的文件也是用Cache去存储,比如RewriterConfiguration里的GetConfig()方法是用CacheKey“RewriterConfig”,但将这个key清除后也没有生效。

之后改成自己的获取方式才可以生效:

 1 /// <summary>
 2         /// GetConfig() returns an instance of the <b>RewriterConfiguration</b> class with the values populated from
 3         /// the Web.config file.  It uses XML deserialization to convert the XML structure in Web.config into
 4         /// a <b>RewriterConfiguration</b> instance.
 5         /// </summary>
 6         /// <returns>A <see cref="RewriterConfiguration"/> instance.</returns>
 7         public static RewriterConfiguration GetConfig()
 8         {
 9             //RewriterConfiguration dd = GetRewriterInfo();
10             //if (HttpContext.Current.Cache["RewriterConfig"] == null)
11             //    HttpContext.Current.Cache.Insert("RewriterConfig", ConfigurationSettings.GetConfig("RewriterConfig"));
12 
13             //return (RewriterConfiguration)HttpContext.Current.Cache["RewriterConfig"];
14             return GetRewriterInfo();
15         }
16 
17         #region 获取伪静态配置
18         private static RewriterConfiguration GetRewriterInfo()
19         {
20             RewriterConfiguration rewriter = new RewriterConfiguration();
21             string urlconfig = System.Web.HttpContext.Current.Server.MapPath("/config/URLRewriter.config");
22             string CacheKey = "URLHtmlConfigWriterCache";
23             System.Web.Caching.Cache objCache = HttpRuntime.Cache;
24             if (objCache[CacheKey] == null)
25             {
26                 XmlDocument doc = new XmlDocument();
27                 doc.Load(urlconfig);
28                 XmlElement root = doc.DocumentElement;
29                 RewriterRuleCollection rules = new RewriterRuleCollection();
30                 XmlNodeList items = root.SelectSingleNode("/RewriterConfig/Rules").ChildNodes;
31                 foreach (XmlNode item in items)
32                 {
33                     XmlNodeList sonItem = item.ChildNodes;
34                     //如果下面还有节点,说明是配置信息,否则则是注释等信息
35                     if (sonItem.Count > 0)
36                     {
37                         RewriterRule rule = new RewriterRule();
38                         rule.LookFor = item["LookFor"].InnerText;
39                         rule.SendTo = item["SendTo"].InnerText;
40                         rules.Add(rule);
41                     }
42                 }
43                 rewriter.Rules = rules;
44 
45                 if (rewriter!=null&&rewriter.rules!=null)
46                 {
47                     objCache.Insert(CacheKey, rewriter);
48                 }
49 
50                 return rewriter;
51             }
52             else
53             {
54                 return (RewriterConfiguration)objCache[CacheKey];
55             }
56         }
57         #endregion
原文地址:https://www.cnblogs.com/hougelou/p/4027392.html