在asp.net中实现URL Rewrite,除了IIS本身带的URL Rewrite Module以外,还有很到其他的解决方案,比如UrlRewritingNET。
UrlRewritingNET号称除了文件扩展名Rewrite需要IIS支持以外,其他所有操作都不需要IIS设置,这当然对虚拟主机的网站来说是非常便利的。
下面看看怎么来部署UrlRewritingNET:
1. 首先将下载的dll放置到bin目录
2. 修改Web.config,增加UrlRewritingNET的相关配置如下:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="urlrewritingnet"
requirePermission="false"
type="UrlRewritingNet.Configuration.UrlRewriteSection, UrlRewritingNet.UrlRewriter"/>
</configSections>
<urlrewritingnet rewriteOnlyVirtualUrls="true"
contextItemsPrefix="QueryString"
defaultProvider="RegEx"
xmlns="http://www.urlrewriting.net/schemas/config/2006/07">
<rewrites>
<add name="category"
virtualUrl="^~/category/(.*)"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/index.html?category=$1"
redirect="Application"
ignoreCase="true"/>
<add name="book"
virtualUrl="^~/book/(.*),index.xml"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/reader.html?book=$1"
redirect="Application"
ignoreCase="true"/>
<add name="categoryAPI"
virtualUrl="^~/api/category/(.*)"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/api/Category.ashx?path=$1"
ignoreCase="true"/>
<add name="bookAPI"
virtualUrl="^~/api/book/(.*)"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/api/Book.ashx?path=$1"
ignoreCase="true"/>
<add name="metaAPI"
virtualUrl="^~/api/meta/(.*)"
rewriteUrlParameter="ExcludeFromClientQueryString"
destinationUrl="~/api/Meta.ashx?path=$1"
ignoreCase="true"/>
</rewrites>
</urlrewritingnet>
<system.web>
<httpModules>
<add name="UrlRewriteModule" type="UrlRewritingNet.Web.UrlRewriteModule, UrlRewritingNet.UrlRewriter"/>
</httpModules>
</system.web>
</configuration>
3. 嵌入Rewrite规则,在<rewrites>中。virtualUrl是正则表达式的虚拟URL,destinationUrl是目标的URL。如果表明redirect,则UrlRewritingNET会通过HTTP 301,302重定位,浏览器显示的网址会有所变化
4. 需要注意的是,需要添加Global.asax,UrlRewritingNET才会生效