IHttpModule是绿叶,IHttpHandler是花。 IHttpHandler按照你的请求生成响应的内容,IHttpModule对请求进行预处理,如验证、修改、过滤等等,同时也可以对响应进行处理。

可能的情形

假 定某组用户在运行某 Web 应用程序的一个个性化版本,并且该应用程序需要一些远程调试或分析。您不能中断服务,但仍需要了解发生的情况。有了性能计数器和内置的跟踪功能可能还不 够。所部署的 ASP.NET 页面有可能根本没有包含或启用跟踪指令。在这种情况下,您需要进行远程干预,注入跟踪代码,这是最基本的要求。
还有一种情形,就是需要临时更改多种页面。对于单个页面,您只需创建旧页面的一个副本并替换它即可。不过,更新多个页面可能就比较困难了,并且维护工作也可能及其复杂。
第三种情形,就是企业策略禁止对源代码进行写操作。在这种情况下,源代码可读,但不可修改。不过,您可以向站点添加扩展。
最后一种情形,也是最复杂并且我真的遇到过的一种情形,即公司运行的 Web 应用程序的源代码由于某种原因不再可用。
可以看出,需要在不访问源代码的情况下修改页面的运行时行为的情形非常多。那么接下来该怎么办呢?
可行的方法

有许多方法可以在不接触源代码的情况下修改正在运行的 ASP.NET 页面。图 1 列出了几种方法。不是所有的方法在任何情形下都有效,而且有些方法可以一起使用。有的方法可能需要编写新的 HTTP 模块或 HTTP 处理程序,有的方法则可能要求对 web.config 文件进行更改。

方法 实现
访问控件树 HTTP 模块
修改页面基类 web.config
控件替换 web.config
构建提供程序 程序集
重定向页面 HTTP 处理程序
重写页面 HTTP 处理程序或 URL 重写

每个 ASP.NET 请求的处理都需要一个专用组件,即 HTTP 处理程序。当在应用程序生命周期内触发 PostMapRequestHandler 事件时,可引用负责处理当前请求的 HTTP 处理程序。

Code pieces:

Code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3: IHttpModule
{
    public Class3()
    {
        //
        // TODO: Add constructor logic here
        //
    }

#region IHttpModule Members

public void Dispose()
    {
        
    }

HttpApplication _context;
    public void Init(HttpApplication context)
    {
        _context = context;
        context.PostMapRequestHandler += new EventHandler(context_PostMapRequestHandler);
        context.EndRequest += new EventHandler(context_EndRequest);
    }

void context_EndRequest(object sender, EventArgs e)
    {
        
    }

void context_PostMapRequestHandler(object sender, EventArgs e)
    {
        if (_context.Context.Handler is Page)
        {
            (_context.Context.Handler as Page).PreInit += new EventHandler(Class3_PreInit);
            (_context.Context.Handler as Page).Load += new EventHandler(Class3_Load);
            (_context.Context.Handler as Page).Unload += new EventHandler(Class3_Unload);
            
        }
    }

void Class3_Unload(object sender, EventArgs e)
    {
        
    }

void Class3_Load(object sender, EventArgs e)
    {
        string ctrlName = "iambox";
        Control ctl = FindControl(sender as Control, ctrlName);
        if (ctl != null)
        {
            ctl.Parent.Controls.Remove(ctl);
        }
    }

void Class3_PreInit(object sender, EventArgs e)
    {
        (sender as Page).Response.Write("How are you?");

Label l = new Label();
        l.Text = "changed by this Label!";
        l.ForeColor = Color.Blue;
        l.Font.Size = 30;
        (sender as Page).Controls.AddAt(0, l);
    }

#endregion

Control FindControl(Control ctl, string ctrlName)
    {        
        if (ctl.ID != null)
        {
            if (ctl.ID.Equals(ctrlName, StringComparison.CurrentCultureIgnoreCase))
                return ctl;
        }

Control controlToFind = null;
        foreach (Control c in ctl.Controls)
        {
            controlToFind = FindControl(c, ctrlName);
            if (controlToFind != null)
                break;
        }

return controlToFind;
    }

}

Code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;
using System.Data.SqlClient;

/// <summary>
/// Summary description for Class2
/// </summary>
public class Class2 : IHttpHandler
{
    public Class2()
    {
        //
        // TODO: Add constructor logic here
        //
    }

#region IHttpHandler Members

public bool IsReusable
    {
        get { return true; }
    }

public virtual void ProcessRequest(HttpContext context)
    {
        context.Response.Write("Hello!");
    }

#endregion
}

HandlerTest.ashx

Code
<%@ WebHandler Language="VB" Class="Handler" %>

Public Class Handler
    Implements IHttpHandler

ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return True
        End Get
    End Property
    
    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        ' Set up the response settings
        context.Response.ContentType = "image/jpeg"
        context.Response.Cache.SetCacheability(HttpCacheability.Public)
        context.Response.BufferOutput = False
        ' Setup the Size Parameter
        Dim size As PhotoSize = PhotoSize.Original
        Select Case context.Request.QueryString("Size")
            Case "S"
                size = PhotoSize.Small
            Case "M"
                size = PhotoSize.Medium
            Case "L"
                size = PhotoSize.Large
            Case Else
                size = PhotoSize.Original
        End Select
        ' Setup the PhotoID Parameter
        Dim id As Int32 = 1
        Dim stream As IO.Stream = Nothing
        If ((Not (context.Request.QueryString("PhotoID")) Is Nothing) _
           AndAlso (context.Request.QueryString("PhotoID") <> "")) Then
            id = [Convert].ToInt32(context.Request.QueryString("PhotoID"))
            stream = PhotoManager.GetPhoto(id, size)
        Else
            id = [Convert].ToInt32(context.Request.QueryString("AlbumID"))
            stream = PhotoManager.GetFirstPhoto(id, size)
        End If
        ' Get the photo from the database, if nothing is returned, get the default "placeholder" photo
        If (stream Is Nothing) Then
            stream = PhotoManager.GetPhoto(size)
        End If
        ' Write image stream to the response stream
        Dim buffersize As Integer = (1024 * 16)
        Dim buffer() As Byte = New Byte((buffersize) - 1) {}
        Dim count As Integer = stream.Read(buffer, 0, buffersize)
        
        Do While (count > 0)
            context.Response.OutputStream.Write(buffer, 0, count)
            count = stream.Read(buffer, 0, buffersize)
            
        Loop
    End Sub
    
End Class

Code


<httpModules>
            <add name="test" type="Class3"/>
        </httpModules>

<httpHandlers>
            <add verb="*" path="pageForbiddenhandler.aspx,ES Major Defects.xlsx" type="System.Web.HttpForbiddenHandler"/>
            <add verb="*" path="pagehandlertest.aspx" type="Class2"/>
        </httpHandlers>

转载于:https://www.cnblogs.com/silva/archive/2009/05/11/1454201.html

IHttpModule IHttpHandler相关推荐

  1. 从.Net类库代码来看Asp.net运行时(转自酷网动力)

    写在前面的话:网上讲Asp.net运行模式的好文章已经很多了,笔者本不用多此一举,另成一文.但从笔者自己的学习经验看,如果学到的这些知识不能对应 到类库中的源代码,印象总归不够深刻,大有隔靴搔痒之感. ...

  2. IHttpModule和IHttpHandler 应用笔记

    ASP.NET 提供了 IHttpHandler 和 IHttpModule 接口,它可使您使用与在 IIS 中所用的 Internet 服务器 API (ISAPI) 编程接口同样强大的 API,而 ...

  3. 个人IHttpHandler,IHttpModule认识

    IHttpHandler 自定义一般处理程序类及配置: 这里只是简单讲讲"可以这么做",对于原理性底层的东西,博客园有详细资料,这里略过.(IIs处理机制,文件处理映射等) 对于一 ...

  4. IHttpModule 与IHttpHandler的区别

    总结的很浅显易懂.转自 IHttpModule与IHttpHandler的区别主要有两点:     1.先后次序.先IHttpModule,后IHttpHandler.     2.对请求的处理上: ...

  5. 【转】Asp.net的生命周期应用之IHttpModule和IHttpHandler

    引言 Http 请求处理流程 和 Http Handler 介绍 这两篇文章里,我们首先了解了Http请求在服务器端的处理流程,随后我们知道Http请求最终会由实现了IHttpHandler接口的类进 ...

  6. IHttpModule与IHttpHandler的区别整理

    先后次序: 先IHttpModule,后IHttpHandler. 注:Module要看你响应了哪个事件,一些事件是在Handler之前运行的,一些  是  在Handler之后运行的 对请求的处理上 ...

  7. IHttpHandler 概述

    IHttpHandler 概述 可能和我一样,很多Asp.Net开发人员都有过Asp的背景,以至于我们在开发程序的时候,通常都是在"页面级"上思考,也就是说我们现在正在做的这个页面 ...

  8. 用自定义IHttpModule实现URL重写

    在本人拙作<ASP.NET夜话>第十二章中探讨过ASP.NET底层运行机制的问题,在该书中本人也讲到过了解一些ASP.NET的低层机制对于我们灵活控制ASP.NET有很大帮助,在该书中本人 ...

  9. IHttpHandler的学习(0-2)

    这个IHttpHandler,要想到asp.net生命周期 ,想到哪个从你发起请求开始,这个请求通过HttpModule------>IHttpHandler的: 执行HttpModule的一系 ...

最新文章

  1. UE5虚幻引擎5中的实时特效学习 Introduction to real time FX in Unreal Engine 5
  2. Haproxy代理配置---传输层
  3. 防止sql注入攻击的方法总结
  4. linux tr 变量大小写,使用tr命令快速达到大小写互换——深圳培训linux
  5. php.ini 相对路径,php中zend相对路径问题
  6. MySQL Innodb引擎和MyIASM引擎的区别
  7. 移动硬盘提示由于IO设备错误,无法运行此项请求要怎么办啊
  8. html 一键发送给微信朋友圈,微信朋友圈如何转发别人说说(朋友圈一键集赞神器)...
  9. 47.0.概率论与数理统计-两个正态总体均值差的置信区间
  10. win10从网络访问计算机没有guest,简单几步解决win10没有权限访问网络资源的问题...
  11. linux tar.7z如何解压,(转)Linux下解压:tar、rar、7z命令
  12. Windows查看ssh公钥方法
  13. 怎么从H5广告页内复制微信号直接调起微信客户端添加好友
  14. react上拉加载更多
  15. RabbitMQ与Erlang版本对应关系
  16. 工作1-2年,月薪3000不可怕,可怕的是能力与之相匹配
  17. 送给计算机老师的话,送给老师的话(精选60句)
  18. jquery手风琴_有史以来最简单的jQuery手风琴
  19. 用QT搭建简单的播放器外壳
  20. HTML5+CSS3 鼠标悬停3D立体图片效果

热门文章

  1. 传统 JDBC 编程详解
  2. layui的登录ajax,layui如何实现登录功能
  3. 安卓新发布机制----app bundle
  4. commons-lang3-RandomUtils
  5. Ubuntu 安装 chrome
  6. [SCOI2005]扫雷(递推)
  7. easyui学习笔记一:主要结构
  8. 使用VNC远程安装CentOS 7操作系统
  9. Junit5集成到SpringBoot工程
  10. Eclipse提速优化方法