url重写整理

asp.net实现url重写(伪静态)

最终效果是,
12345.html 替换 show.aspx?id=12345

也可以实现百度空间的
http://hi.baidu.com/wu1987116
替换
http://hi.baidu.com/index.aspx?UserName=wu1987116

程序要调整的部分只有两块。
一是web.config文件。
二是链接地址。
所需urlrewrite.dll


第一步:将urlrewrite.dll引用进来。
第二步:修改web.config
这一步要修改几个地方。要注意位置是不同的
1. 在web.config文件中加入如下代码,注意要放在<configuration>下面.
<configSections>
<section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
</configSections>
其中
<section name="RewriterConfig"
type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
用于指定配置节"RewriterConfig"的处理程序类的名称为”URLRewriter.Config.RewriterConfigSerializerSectionHandler”,该类存在于bin目录
下的URLRewriter.dll文件中

2. 在web.config文件中的system.web节点下加入如下代码
<httpHandlers>
<add verb="*" path="*.html" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
<add verb="*" path="*" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
</httpHandlers>
这段代码的意思是:将文件扩展名为.html和任意扩展名(包括无扩展名,不包括*.html,因为这个位置在上面会先处理)的文件的所有 HTTP 请求映射
到类 URLRewriter.RewriterFactoryHandler,注意顺序,按从上到下执行,如果path="*"在上面的话,则下面的html映射则无效,下面步骤中有映射到那
个页面的设置

3. 重写url(重写规则)
和1一样 ,同样是放在<configuration>节点下面
<RewriterConfig>
<Rules>
<!--一个参数-->
<RewriterRule>
<LookFor>~/read/(.[\d]*).html</LookFor>
<SendTo>~/WebForm1.aspx?UserID=$1</SendTo>
</RewriterRule>
<!--两个参数-->
<RewriterRule>
<LookFor>~/read/(\d{2,})-(\d{1,})\.html</LookFor>
<SendTo>~/WebForm1.aspx?UserID=$1 &amp;name=$2</SendTo>
</RewriterRule>
<!--三个个参数-->
<RewriterRule>
<LookFor>~/read/(\d+)-(\d+)-(\d+)\.html</LookFor>
<SendTo>~/WebForm1.aspx?UserID=$1 &amp;name=$2 &amp;age=$3</SendTo> 注意其中&amp;前面有一个空格,切忌
</RewriterRule>
</Rules>
</RewriterConfig>
效果:
当访问http://127.0.0.1/123.html时,实际访问的是http://127.0.0.1/Shownews.aspx?ShowID=123
访问http://127.0.0.1/任意字符时,实际访问的是http://127.0.0.1/blog.aspx?UserName=任意字符

<LookFor>~/read/(.[\d]*).html</LookFor>
<SendTo>~/WebForm1.aspx?UserID=$1</SendTo>
意思是把第一个路径转成另一个路径。其中<LookFor>()中的正则表达式就是第二句中的参数$1 .
同样也可以用$2 $3来表示<LookFor>中第二 第三个()中的参数。
多个参数:
<!--两个参数-->
<RewriterRule>
<LookFor>~/read/(\d{2,})-(\d{1,})\.html</LookFor>
<SendTo>~/WebForm1.aspx?UserID=$1 &amp;name=$2</SendTo>
</RewriterRule>
<!--三个个参数-->
<RewriterRule>
<LookFor>~/read/(\d+)-(\d+)-(\d+)\.html</LookFor>
<SendTo>~/WebForm1.aspx?UserID=$1 &amp;name=$2 &amp;age=$3</SendTo>
</RewriterRule>
第三步:在页面程序中可以这样写:
<a href="news_<%=newsid%>.html" target="_blank">新闻标题</a>

完成上面三个步骤就可以轻松实现URL重写了,不过需要注意的是:如果发布网站的话,你会发现你的URL重写有可能会失效,如果失效的话就需要您
设置一下IIS:
打开IIS,主目录-〉配置-〉映射-〉点击“插入”通配符应用程序映射-〉选择“C:\WINDOWS\Microsoft.NET\Framework
\v2.0.50727\aspnet_isapi.dll”,文件类型写为.html
然后把勾选去掉(一定要去掉),然后确定。
上面设置完毕之后,就可以正常浏览了。

 

ps:如果要把规则单独写在一个xml中可以使用configSource属性来指定目录,建议放在App_Data目录下,安全性更高.
<RewriterConfig configSource="App_Data\guize.xml" />

 

 

 

 

posted @ 2012-02-20 15:39  kelin418  阅读(324)  评论(0编辑  收藏  举报