IHttpModule和IHttpHandler 应用笔记
关于HttpModule的注册、应用方法请参看我的另一篇博文:
使用HTTP模块扩展 ASP.NET 处理
关于IHttpHandler的应用,我们先从它的注册方法讲起。
当你建立了一个实现了Ihttphandler接口的类后,可以在网站的web.config文件中注册这个httphandler
示例如下:
<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.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;
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 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结点,如下:
<httpHandlers>
<add verb="*" path="download.aspx" type="DownloadHandler" />
</httpHandlers>
</system.web>
5. 现在新建一个aspx页面,对文件进行下载:
Default.aspx代码如下:
<%@ 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.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 应用笔记相关推荐
- IHttpModule 与IHttpHandler的区别
总结的很浅显易懂.转自 IHttpModule与IHttpHandler的区别主要有两点: 1.先后次序.先IHttpModule,后IHttpHandler. 2.对请求的处理上: ...
- IHttpModule与IHttpHandler的区别整理
先后次序: 先IHttpModule,后IHttpHandler. 注:Module要看你响应了哪个事件,一些事件是在Handler之前运行的,一些 是 在Handler之后运行的 对请求的处理上 ...
- 【转】Asp.net的生命周期应用之IHttpModule和IHttpHandler
引言 Http 请求处理流程 和 Http Handler 介绍 这两篇文章里,我们首先了解了Http请求在服务器端的处理流程,随后我们知道Http请求最终会由实现了IHttpHandler接口的类进 ...
- 用自定义IHttpModule实现URL重写
在本人拙作<ASP.NET夜话>第十二章中探讨过ASP.NET底层运行机制的问题,在该书中本人也讲到过了解一些ASP.NET的低层机制对于我们灵活控制ASP.NET有很大帮助,在该书中本人 ...
- 《ASP.NET MVC 5 高级编程》 - 学习笔记
<ASP.NET MVC 5 高级编程> ========== ========== ========== [作者] (美) Jon Galloway (美) Brad Wilson (美 ...
- HttpHandler与HttpModule区别
ASP.Net处理Http Request时,使用Pipeline(管道)方式,由各个HttpModule对请求进行处理,然后到达 HttpHandler,HttpHandler处理完之后,仍经过Pi ...
- Taurus.MVC 支持Asp.Net Core 的过程
前言: 这些天,似乎.NET Core相关的新闻和文章经常在我眼前晃~~~ 昨天,微软又发布了.Core 2.1,又愰了一下,差点没亮瞎我的眼睛. 好吧,大概是上天给我的暗示,毕竟 CYQ.Data ...
- asp.net 页面全生命周期
.Net 托管代码和非托管代码的区别 后台代码隐藏/显示前台控件 .Net 页面生命周期 2012-03-21 13:31:08| 分类: .NET | 标签:.net 页面生命周期 c# ...
- asp.net Forums 之HttpHandler和HttpModule
我们先说说IHttpHandler和IHttpModule这两个接口. 微软的解释为: IHttpHandler: 定义 ASP.NET 为使用自定义 HTTP 处理程序同步处理 HTTP Web 请 ...
最新文章
- python机器学习可视化工具Yellowbrick介绍及平行坐标图实战示例
- 基于图文界面的蓝牙扫描工具btscanner
- 如何基于K8s构建下一代DevOps平台?
- c# wpf 面试_WPF 基础面试题及答案(一)
- linux网络编程之inet_pton和inet_ntop函数
- 好用!一键生成数据库文档,这个开源的文档生成工具值得了解
- 数学建模(7)---建模开始
- 逆向libbaiduprotect(二)
- sizeo(结构体)的问题
- CentOS6.2(64bit)下mysql5.6.16主从同步配置
- Java程序连接数据库
- 2022自动驾驶竞赛WAD介绍 CVPR 2022 Workshop on Autonomous Driving
- 华为交换机eth口作用_华为交换机 eth-trunk
- django安装mysqlclient报错mand errored out with exit status 1: python setup.py egg_info Check the logs f
- U盘图标不显示(转)
- 怎样在VS2005中添加Flash控件
- Unable to attach or mount volumes ... timed out waiting for the condition
- 芯片TOPS的真实性 - 解释 ( 标量 ,矢量, 张量)
- 计算机考研408每日一题 day76
- js简单实现拦截访问指定网址