asp .net URL重写

View Code
截获请求代码
⒈要重写,首先是截获url请求,然后分析当时的url,最后跳转到相应的页面.所以我们第一步是要截获url请求.为此新建一个类库叫URL,在该类库中引用URLRewriter.dll.新建一个类myrewritter.cs,代码如下
namespace URL
{
public class myrewritter : URLRewriter.BaseModuleRewriter
{
protected override void Rewrite(string requestedPath,HttpApplication app)
{
if (requestedPath.Contains("news/2011/3/2.html"))
app.Context.RewritePath("/news.aspx?id=2&year=2011&month=3");
else
app.Context.RewritePath("/here.aspx");
}
}
}
可以看到该类继承了URLRewriter.BaseModuleRewriter。只要当前的url请求是news/2011/3/2.html,我们就会将页面重写到/news.aspx?id=2&year=2011&month=3.
这只是一个简单的例子,实际上对于url的判断,一般是用正则表达式来完成.而页面和页面间的对应关系,可能需要通过查询数据库完成.
web.config代码
接下来在网站项目中引用这个类库.然后修改下web.config,下面的:
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<httpModules>
<add type="URL.myrewritter" name="URL" />
</httpModules>
<compilation debug="true" />
<authentication mode="Windows" />
</system.web>
</configuration>
步骤总结
大家可以看到我新加了个httpModules.这个的作用是,如果有url请求,asp/net会先把请求传到你指定的这个类中来.add那一行了,前面的是要接收请求的类,后面的是这个类所在的dll的名字.
添加完这一句后,一切就快结束了.由于我们要处理的是.html的页面,所以需要配置下iis.因为默认asp/net的处理引擎不会管.html.我们要做的是用处理asp .net的那个程序来处理html页面.打开iis.找到你的网站,点右键打开属性.找到主目录(Home Directory),打开配置(Configuration)对话框. 在Application extensions列表里找到.aspx,点击编辑(Edit...),复制Executable框的内容。
原文地址:https://www.cnblogs.com/spider024/p/3020016.html