URLRewriter修改使你更容易理解重写原理
在上一篇,我感觉有的地方不是太好理解,所以我在这里修改了一下,更通俗易懂了,为了让更容易理解。 web.config中configSections中添加这个这个节点,根据这个节点 ,你可以看出创建自定义的节点是什么样子的, <sectionGroup name="RewriterConfig"> <section name="Rule" type="WebApplication1.RewriterConfigSerializerSectionHandler,WebApplication1"/> </sectionGroup> <RewriterConfig> <Rule> <RewriterRule> <LookFor>~/About-(\d+).html</LookFor> <SendTo>~\About.aspx?id=$1</SendTo> </RewriterRule> <RewriterRule> <LookFor>~/About-(\d+)-(\d+).html</LookFor> <SendTo>~\About.aspx?id=$1&t=$2</SendTo> </RewriterRule> </Rule> </RewriterConfig>
这一点他们必须相同。
同样的你必须创建一个RewriterConfigSerializerSectionHandler去实IConfigurationSectionHandler接口 public class RewriterConfigSerializerSectionHandler : IConfigurationSectionHandler { public object Create(object parent, object configContext, XmlNode section) { //// Create an instance of XmlSerializer based on the RewriterConfiguration type... //XmlSerializer ser = new XmlSerializer(typeof(RewriterConfigss)); //// Return the Deserialized object from the Web.config XML //return ser.Deserialize(new XmlNodeReader(section)); RewriterRule para = null; IList<RewriterRule> list = new List<RewriterRule>(); for (int i = 0; i < section.ChildNodes.Count; i++) { para = new RewriterRule(); XmlNode xm = section.ChildNodes[i]; para.SendTo= xm.SelectSingleNode("SendTo").InnerText; para.LookFor = xm.SelectSingleNode("LookFor").InnerText; list.Add(para); } return list; } } 上面注释是url重写的源码,在这里大家可以看出我修改了。这个样子更容易被理解 public class RewriterConfigss { //public RewriterRuleCollection Rules { get; set; } /// <summary> /// 该方法从web.config中读取规则集合,并使用了Cache以避免频繁IO操作 /// </summary> /// <returns></returns> public static IList<RewriterRule> GetConfig() { //使用缓存 if (HttpContext.Current.Cache["RewriterRule"] == null) HttpContext.Current.Cache.Insert("RewriterRule", ConfigurationManager.GetSection("RewriterConfig/Rule")); return ((IList<RewriterRule>)HttpContext.Current.Cache["RewriterRule"]); } }
}
ConfigurationManager.GetSection("RewriterConfig/Rule")就这点要注意的是,这么写是为了他直接获得就是里面那些RewriterRule节点集合
就这些了,其他地方和上一遍中的代码一样。