博客
关于我
ASP.NET基础之HttpHandler学习
阅读量:522 次
发布时间:2019-03-07

本文共 5323 字,大约阅读时间需要 17 分钟。

ASP.NET HttpHandler 开发指南

一、HttpHandler 理论知识

HttpHandler 在 ASP.NET 开发中扮演着至关重要的角色。它定义了处理 HTTP 请求的标准接口,区别于 HttpModule,HttpHandler 实现类会通过“覆盖”机制与系统 HttpHandler 统合。

在处理 HTTP 请求时,ASP.NET Framework 会将请求传递至 HttpHandler 容器,并调用其 ProcessRequest 方法。对于 ASPX 页面,默认的处理类是 System.Web.UI.PageHandlerFactory,负责解析和处理页面内容。

每个 HTTP 请求最终都会交给一个 HttpHandler 实现类的 ProcessRequest 方法来处理。开发者可以自定义 HttpHandler 来处理特殊文件或逻辑需求。自定义的 HttpHandler 必须实现 IHttpHandler 接口,其中 IsReusable 属性控制是否可以重复使用实例,ProcessRequest 方法则接收 HttpContext 上下文,用于操作请求、响应和服务器相关资源。

二、Handler.aspx 的一般程序处理类

在实际开发中,Handler.aspx 类是常用的 HttpHandler 实现。在 VS 中新建该类时,通常会看到以下代码:

public class Handler : IHttpHandler
{
public bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello world");
}
}

需要注意的是,使用 Handler.aspx 类时,无法直接访问 Session 值。例如,以下代码无法读取 Session 数据:

public partial class NoSessionHandler : Page, IHttpHandler
{
protected void Page_Load(object sender, EventArgs e) { }
public new bool IsReusable { get { return false; } }
public new void ProcessRequest(HttpContext context)
{
object sessionValue = context.Session["NoSessionHandler"];
string result = string.Empty;
if (sessionValue != null)
{
result = sessionValue.ToString();
}
else
{
result = "没有实现接口,Session 的值无法读到!";
}
context.Response.ContentType = "text/plain";
context.Response.Write(result);
}
}

要实现 Session 数据的读取,需额外实现 IRequiresSessionState 接口:

using System.Web.SessionState;
public partial class NoSessionHandler : Page, IHttpHandler, IRequiresSessionState
{
protected void Page_Load(object sender, EventArgs e) { }
public new bool IsReusable { get { return false; } }
public new void ProcessRequest(HttpContext context)
{
object sessionValue = context.Session["NoSessionHandler"];
string result = string.Empty;
if (sessionValue != null)
{
result = sessionValue.ToString();
}
else
{
result = "没有实现接口,Session 的值无法读到!";
}
context.Response.ContentType = "text/plain";
context.Response.Write(result);
}
}

三、自定义 HttpHandler 开发

要开发自定义 HttpHandler,只需遵循以下步骤:

  • 实现接口:继承 IHttpHandler 并实现 ProcessRequest 方法。
  • 配置文件:在 Web.config 中注册自定义的 HttpHandler。
  • 3.1 自定义后缀类型访问示例

    创建一个 MyHttpHandler 类:

    namespace TestModule2.App_Code
    {
    public class MyHttpHandler : IHttpHandler
    {
    public bool IsReusable { get { return true; } }
    public void ProcessRequest(HttpContext context)
    {
    HttpRequest request = context.Request;
    HttpResponse response = context.Response;
    response.Write("这个是自定义的 HttpHandler");
    response.Write("访问 URL 地址:" + request.Url.Segments[2]);
    string FileStr = request.PhysicalPath;
    if (File.Exists(FileStr))
    {
    response.Write("以下是文件 Test.Coffee 的内容");
    FileInfo fileInfo = new FileInfo(FileStr);
    StreamReader reader = new StreamReader(FileStr, Encoding.Default);
    string StrLine = string.Empty;
    while (!string.IsNullOrEmpty(StrLine = reader.ReadLine()))
    {
    response.Write(StrLine);
    }
    reader.Close();
    }
    else
    {
    response.Write("文件不存在");
    }
    }
    }
    }

    在项目中新建一个 Test.Coffee 文件,并在 Web.config 中注册:

    3.2 实现图片打水印功能

    创建一个 WaterMarkHandler 类:

    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Web;
    namespace TestModule2.App_Code
    {
    public class WaterMarkHandler : IHttpHandler
    {
    public WaterMarkHandler() { }
    public bool IsReusable { get { return true; } }
    public void ProcessRequest(HttpContext context)
    {
    string imagePath = context.Request.PhysicalPath;
    Image image = null;
    if (File.Exists(imagePath))
    {
    string text = "给图片增加水印 [Coffee]";
    int fontSize = 8;
    Font font = new Font("宋体", fontSize);
    image = Image.FromFile(imagePath);
    Graphics g = Graphics.FromImage(image);
    SizeF size = g.MeasureString(text, font);
    if (size.Width > image.Width || size.Height > image.Height)
    {
    // 字体太大,无法添加水印
    }
    else
    {
    Brush brush = Brushes.SkyBlue;
    g.DrawString(text, font, brush, image.Width - size.Width, image.Height - size.Height);
    g.Dispose();
    }
    }
    else
    {
    imagePath = context.Server.MapPath("~/Images/6.png");
    image = Image.FromFile(imagePath);
    }
    image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
    }
    }
    }

    Web.config 中注册水印处理:

    通过以上方法,可以轻松实现自定义 HttpHandler,扩展 ASP.NET 应用的功能。

    转载地址:http://zsejz.baihongyu.com/

    你可能感兴趣的文章
    MySQL 查看有哪些表
    查看>>
    mysql 查看锁_阿里/美团/字节面试官必问的Mysql锁机制,你真的明白吗
    查看>>
    MySql 查询以逗号分隔的字符串的方法(正则)
    查看>>
    MySQL 查询优化:提速查询效率的13大秘籍(避免使用SELECT 、分页查询的优化、合理使用连接、子查询的优化)(上)
    查看>>
    mysql 查询数据库所有表的字段信息
    查看>>
    【Java基础】什么是面向对象?
    查看>>
    mysql 查询,正数降序排序,负数升序排序
    查看>>
    MySQL 树形结构 根据指定节点 获取其下属的所有子节点(包含路径上的枝干节点和叶子节点)...
    查看>>
    mysql 死锁 Deadlock found when trying to get lock; try restarting transaction
    查看>>
    mysql 死锁(先delete 后insert)日志分析
    查看>>
    MySQL 死锁了,怎么办?
    查看>>
    MySQL 深度分页性能急剧下降,该如何优化?
    查看>>
    MySQL 深度分页性能急剧下降,该如何优化?
    查看>>
    MySQL 添加列,修改列,删除列
    查看>>
    mysql 添加索引
    查看>>
    MySQL 添加索引,删除索引及其用法
    查看>>
    mysql 状态检查,备份,修复
    查看>>
    MySQL 用 limit 为什么会影响性能?
    查看>>
    MySQL 用 limit 为什么会影响性能?有什么优化方案?
    查看>>
    MySQL 用户权限管理:授权、撤销、密码更新和用户删除(图文解析)
    查看>>