实现的最终的效果是访问http://zl.wq.com/newsd/1983/跳转到http://zl.wq.com/NewsInfo.aspx?newsid=1983
首先第一步先添加处理Url请求的类,此类需继承IHttpModule
public class ZywUrlWriter : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
protected void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
HttpContext context = application.Context; //上下文
string url = context.Request.Url.LocalPath; //获得请求URL
Regex articleRegex = new Regex("/newsd/[0-9]+"); //定义规则
if (articleRegex.IsMatch(url))
{
url = url.TrimEnd('/');
string paramStr = url.Substring(url.LastIndexOf('/') + 1);
int NewsId = Utils.ConvertToInt(paramStr);
if (NewsId > 0)
context.RewritePath("/NewsInfo.aspx?newsid=" + NewsId.ToString());
}
//else
//{
// context.RewritePath("/Default.aspx");
//}
}
public void Dispose() { }
}
第二步、修改webconfig和iis配置
(1)iis7以上版本且应用程序池选中集成模式,只需修改webconfig
在system.webServer下的modules节点添加子节点,内容是<add name="UrlReWriter" type="DataLay.ZywUrlWriter,DataLay" /> 。name的值可以任意指定 type的值分两部分,逗号前面的明显就是添加的url处理类文件的目录,逗号后面的值是添加类所在的项目名称
<modules>
<remove name="ScriptModule" />
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add name="UrlReWriter" type="DataLay.ZywUrlWriter,DataLay" />
</modules>
(2)如果是iis7以上的经典模式
1、修改webconfig,和集成模式不同,经典模式需要把新加的内容放在system.web下的httpModules中。
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add name="UrlReWriter" type="DataLay.ZywUrlWriter,DataLay" />
</httpModules>
2、修改IIS配置,在IIS的处理程序映射下添加通配符脚本映射(注意是通配符脚本映射 不是脚本映射名字很像但是添加后效果不一样)
请求路径填*(星号)。可执行文件选择aspnet_isapi.dll。有的机器上.net framwork有32位和64位两个版本。如果选择64位下的不可以的话可以换到32位的试一下。
(3)iis6版本下的操作
1、webconfig的配置和上面的iis7版本经典模式下的配置一样都是放到httpModules下
2、在iis中插入通配符应用程序映射
可执行文件选择的是aspnet_isapi.dll。需要注意的是把确定文件是否存在的选项给取消选中。