ASP.NET 提供了 IHttpHandler 和 IHttpModule 接口,它可使您使用与在 IIS 中所用的 Internet 服务器 API (ISAPI) 编程接口同样强大的 API,而且具有更简单的编程模型。HTTP 处理程序对象与 IIS ISAPI 扩展的功能相似,而 HTTP 模块对象与 IIS ISAPI 筛选器的功能相似。
ASP.NET 将 HTTP 请求映射到 HTTP 处理程序上。每个 HTTP 处理程序都会启用应用程序内单个的 HTTP URL 处理或 URL 扩展组处理。HTTP 处理程序具有和 ISAPI 扩展相同的功能,同时具有更简单的编程模型。
HTTP 模块是处理事件的程序集。ASP.NET 包括应用程序可使用的一组 HTTP 模块。例如,ASP.NET 提供的 SessionStateModule 向应用程序提供会话状态服务。也可以创建自定义的 HTTP 模块以响应 ASP.NET 事件或用户事件。

关于HttpModule的注册、应用方法请参看我的另一篇博文:

使用HTTP模块扩展 ASP.NET 处理

关于IHttpHandler的应用,我们先从它的注册方法讲起。

当你建立了一个实现了Ihttphandler接口的类后,可以在网站的web.config文件中注册这个httphandler

示例如下:

    <httpHandlers>
            <remove verb="*" path="*.asmx"/>
            <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add verb="*" path="*.ho" type="WebApplication2.HelloHandler,WebApplication2"/>
        </httpHandlers>

其中最后一行  <add verb="*" path="*.ho" type="WebApplication2.HelloHandler,WebApplication2"/>
便是我们手工加入的内容,WebApplication2.HelloHandler是实现了IhttpHandler接口的一个类,Path属性表示的是映射的文件格式。

这样注册好之后,如果从网站请求任何带后缀名.ho的文件时,就会转到WebApplication2.HelloHandler类进行处理。

而WebApplication2.HelloHandler的内容可以是在网页上打印一行文本(如下面代码),也可以是下载一个文件,反正在httphandler里面你可以控制response对象的输出。

下面代码示例打印一行文字的WebApplication2.HelloHandler源码:

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace WebApplication2
{
    public class HelloHandler:IHttpHandler
    {
        #region IHttpHandler
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            context.Response.Write("<html>");
            context.Response.Write("<body>");
            context.Response.Write("<b>Response by HelloHandler!</B>");
            context.Response.Write("</body>");
            context.Response.Write("</html>");
        }

public bool IsReusable
        {
            get
            { return true; }
        }
        #endregion
    }
}

以下内容为转载的IhttpHandler示例:利用IhttpHandler实现文件下载

1. 首先新建一个用于下载文件的page页,如download.aspx,里面什么东西也没有。

2. 添加一个DownloadHandler类,它继承于IHttpHandler接口,可以用来自定义HTTP 处理程序同步处理HTTP的请求。

using System.Web;
using System;
using System.IO;
public class DownloadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        HttpResponse Response = context.Response;
        HttpRequest Request = context.Request;

System.IO.Stream iStream = null;

byte[] buffer = new Byte[10240];

int length;

long dataToRead;

try
        {
            string filename = FileHelper.Decrypt(Request["fn"]); //通过解密得到文件名

string filepath = HttpContext.Current.Server.MapPath("~/") + "files/" + filename; //待下载的文件路径

iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                System.IO.FileAccess.Read, System.IO.FileShare.Read);
            Response.Clear();

dataToRead = iStream.Length;

long p = 0;
            if (Request.Headers["Range"] != null)
            {
                Response.StatusCode = 206;
                p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
            }
            if (p != 0)
            {
                Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long) (dataToRead - 1)).ToString() + "/" + dataToRead.ToString());
            }
            Response.AddHeader("Content-Length", ((long) (dataToRead - p)).ToString());
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(Path.GetFileName(filename))));

iStream.Position = p;
            dataToRead = dataToRead - p;

while (dataToRead > 0)
            {
                if (Response.IsClientConnected)
                {
                    length = iStream.Read(buffer, 0, 10240);

Response.OutputStream.Write(buffer, 0, length);
                    Response.Flush();

buffer = new Byte[10240];
                    dataToRead = dataToRead - length;
                }
                else
                {
                    dataToRead = -1;
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write("Error : " + ex.Message);
        }
        finally
        {
            if (iStream != null)
            {
                iStream.Close();
            }
            Response.End();
        }
    }

public bool IsReusable
    {
        get { return true; }
    }
}

3. 这里涉及到一个文件名加解密的问题,是为了防止文件具体名称暴露在状态栏中,所以添加一个FileHelper类,代码如下:

public class FileHelper
{
    public static string Encrypt(string filename)
    {
        byte[] buffer = HttpContext.Current.Request.ContentEncoding.GetBytes(filename);
        return HttpUtility.UrlEncode(Convert.ToBase64String(buffer));
    }

public static string Decrypt(string encryptfilename)
    {
        byte[] buffer = Convert.FromBase64String(encryptfilename);
        return HttpContext.Current.Request.ContentEncoding.GetString(buffer);
    }
}

利用Base64码对文件名进行加解密处理。

4. 在Web.config上,添加httpHandlers结点,如下:

<system.web>
  <httpHandlers>
    <add verb="*" path="download.aspx" type="DownloadHandler" />
  </httpHandlers>
</system.web>

5. 现在新建一个aspx页面,对文件进行下载:

Default.aspx代码如下:

Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>文件下载</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:HyperLink ID="link" runat="server" Text="文件下载"></asp:HyperLink>
    </div>
    </form>
</body>
</html>

Default.aspx.cs代码如下:

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;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = FileHelper.Encrypt("DesignPattern.chm");
        link.NavigateUrl = "~/download.aspx?fn=" + url;
    }
}

这样就实现了文件下载时,不管是什么格式的文件,都能够弹出打开/保存窗口。

IHttpModule和IHttpHandler 应用笔记相关推荐

  1. IHttpModule 与IHttpHandler的区别

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

  2. IHttpModule与IHttpHandler的区别整理

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

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

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

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

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

  5. 《ASP.NET MVC 5 高级编程》 - 学习笔记

    <ASP.NET MVC 5 高级编程> ========== ========== ========== [作者] (美) Jon Galloway (美) Brad Wilson (美 ...

  6. HttpHandler与HttpModule区别

    ASP.Net处理Http Request时,使用Pipeline(管道)方式,由各个HttpModule对请求进行处理,然后到达 HttpHandler,HttpHandler处理完之后,仍经过Pi ...

  7. Taurus.MVC 支持Asp.Net Core 的过程

    前言: 这些天,似乎.NET Core相关的新闻和文章经常在我眼前晃~~~ 昨天,微软又发布了.Core 2.1,又愰了一下,差点没亮瞎我的眼睛. 好吧,大概是上天给我的暗示,毕竟 CYQ.Data  ...

  8. asp.net 页面全生命周期

    .Net 托管代码和非托管代码的区别 后台代码隐藏/显示前台控件 .Net 页面生命周期 2012-03-21 13:31:08|  分类: .NET |  标签:.net  页面生命周期  c#  ...

  9. asp.net Forums 之HttpHandler和HttpModule

    我们先说说IHttpHandler和IHttpModule这两个接口. 微软的解释为: IHttpHandler: 定义 ASP.NET 为使用自定义 HTTP 处理程序同步处理 HTTP Web 请 ...

最新文章

  1. python机器学习可视化工具Yellowbrick介绍及平行坐标图实战示例
  2. 基于图文界面的蓝牙扫描工具btscanner
  3. 如何基于K8s构建下一代DevOps平台?
  4. c# wpf 面试_WPF 基础面试题及答案(一)
  5. linux网络编程之inet_pton和inet_ntop函数
  6. 好用!一键生成数据库文档,这个开源的文档生成工具值得了解
  7. 数学建模(7)---建模开始
  8. 逆向libbaiduprotect(二)
  9. sizeo(结构体)的问题
  10. CentOS6.2(64bit)下mysql5.6.16主从同步配置
  11. Java程序连接数据库
  12. 2022自动驾驶竞赛WAD介绍 CVPR 2022 Workshop on Autonomous Driving
  13. 华为交换机eth口作用_华为交换机 eth-trunk
  14. django安装mysqlclient报错mand errored out with exit status 1: python setup.py egg_info Check the logs f
  15. U盘图标不显示(转)
  16. 怎样在VS2005中添加Flash控件
  17. Unable to attach or mount volumes ... timed out waiting for the condition
  18. 芯片TOPS的真实性 - 解释 ( 标量 ,矢量, 张量)
  19. 计算机考研408每日一题 day76
  20. js简单实现拦截访问指定网址

热门文章

  1. 如何在Debian 8/7上安装PostgreSQL 9.6
  2. 自适应滤波:最小二乘法
  3. SQL Server -- LIKE模糊查询
  4. ITOO4.1之缓存—分布式缓存Memcached学习(理论篇)
  5. Java并发——线程间通信与同步技术
  6. ftp 的三种数据传输模式
  7. 用GDB调试程序(转)
  8. 纽约州金融服务局(NYDFS)为比特币现金(BCH)打开绿灯
  9. [JZOJ] 5837.Omeed
  10. awk算术运算一例:统计hdfs上某段时间内的文件大小