ASP.NET过滤器、URL重写

 过滤器可以对指定的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>

转载于:https://www.cnblogs.com/huangshuhua/p/6265624.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值