您的位置:首页 > 编程语言 > ASP

ASP.NET过滤器、URL重写

2017-01-09 16:11 281 查看
 过滤器可以对指定的URL访问进行拦截,并执行过滤器的方法,根据实际应用情况,在过滤器中修改请求的代码、判断会话信息,也可以做权限控制。

 一:编写过滤器,实现URL重写并配置过滤

 编写过滤器,就是编写一个过滤器类,即HttpModule模块。应该实现IHttpModule基类,并重写Init方法。参考代码如下:

 1、添加引用System.Web,导入命名空间using System.Web;2、实现IHttpModule接口,重写Init方法;3、在web.config中找到<httpModules></httpModules>,添加<add name="自定义" type="命名空间名.类名,命名空间名"/>。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
namespace Modules
{
public class MyModule:IHttpModule
{
#region IHttpModule 成员
public void Dispose()
{
}
public void Init(HttpApplication context)
{
//通过委托注册事件
context.BeginRequest += MyBeginRequest;
}
#endregion
void MyBeginRequest(object sender,EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
string requestPath = app.Context.Request.Path;//获得请求的URL,例:/WebSite1/Login.6html
string fileName = System.IO.Path.GetFileName(requestPath);//获得路径中的文件名,Login.6html
Regex reg = new Regex("Login.(\\d+)html");
if (reg.IsMatch(requestPath))
{
Match match = reg.Match(requestPath);
string id = match.Groups[1].Value;
string newPath = "Login.aspx?id=" + id;
app.Context.RewritePath(newPath);
}
}
}
}


HttpApplication事件:BeginRequest(程序员最早能够处理的事件),acquireRequestState(能使用到session),PostRequestHandlerExecute(能使用到session),EndRequest等等。

 二、微软的URLRewriter实现URL重写

 把组件URLRewriter.dll拷到应用程序的bin目录下,然后在web.config下加入如下代码:
 在<configuration></configuration>中加入:

<configSections> <sectionname="RewriterConfig"type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter"/>
</configSections>
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>~/("d{4})/("d{2})/Default".aspx</LookFor>
<SendTo>~/Default.aspx?ID=$1</SendTo>
</RewriterRule>
</Rules>
</RewriterConfig>


 然后在<system.web></system.web>中加入:

<httpHandlers>
<addverb="*"path="*.aspx"
type="URLRewriter.RewriterFactoryHandler, URLRewriter"/>
</httpHandlers>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: