(原创)Urlrewrite 独立配置文件的使用方法

最近有朋友在开发项目时使用了microsoft的URLRewrite.dll,但在使用中遇到一个问题,那就是所有的匹对规则必须写在web.config文件,有时很小的一个改动就会导致web.config出错,从而使整个站点都将受到影响,而且过多的匹对规则也会使web.config文件过大,平时在使用时也有过多的不便。那么是否有方法可以将匹对规则写到一个独立的配置文件中呢,答案是肯定的。但很可惜microsoft的urlrewrite.dll并没有提供这样的那功能。那么就只能依靠我们自己来扩展这个功能。

首先到microsoft官网上下载urlrewrite.dll文件。下载地址:http://download.microsoft.com/download/0/4/6/0463611e-a3f9-490d-a08c-877a83b797cf/MSDNURLRewriting.msi
下载完后打开URLRewriter项目。将会看到以下目录结构:

其中config/CustomRewriterConfigSerializerSectionHandler.cs即为我们自定义的文件。其他文件都不需要修改

CustomRewriterConfigSerializerSectionHandler.cs中的代码如下:

 

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

namespace URLRewriter.Config
{
    
public class CustomRewriterConfigSerializerSectionHandler:IConfigurationSectionHandler
    {
        
#region IConfigurationSectionHandler 成员

        
public object Create(object parent, object configContext, XmlNode section)
        {
            
string sourcePath = section.Attributes["ConfigSource"].Value;
            sourcePath 
= System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, sourcePath);

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

            XmlDocument xmlDoc 
= new XmlDocument();
            xmlDoc.Load(sourcePath);
            
// Return the Deserialized object from the Web.config XML
            return ser.Deserialize(new XmlNodeReader(xmlDoc));
        }

        
#endregion
    }
}

 

OK。修改完成,编译生成urlrewriter.dll文件。

 

至此urlrewriter.dll的修改已经完成,下面我将介绍一下具体的使用方法:

1、项目引用urlrewriter.dll文件,

2、web.config配置如下。

<configSections>
    
<section name="RewriterConfig" type="URLRewriter.Config.CustomRewriterConfigSerializerSectionHandler, URLRewriter" />
</configSections>
<RewriterConfig ConfigSource="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&amp;month=$2&amp;day=$3</SendTo>
      
</RewriterRule>
    
</Rules>
  
</RewriterConfig>

 

OK,现在去运行下项目试试,是不是已经达到你想要的效果了呢。

希望该篇能为大家带来一些帮助!

 

 

 

 

 

 

 

posted on 2011-02-24 14:30  冬日阳光  阅读(4621)  评论(2编辑  收藏  举报

导航