HttpHandler(处理程序) 和 HttpModule(托管模块)
ASP.NET其请求处理过程是基于管道模型的,这个管道模型由多个HttpModule和HttpHandler组成。
在整个生命周期中,它们大致的执行过程是这样的:client端发送页面请求,被IIS的某个进程截获,它根据申请的页面后缀(.aspx)不同,调用不同的页面处理程序(.asp->asp.dll;.aspx->ISAPI.dll),而页面处理程序在处理过程中,则要经历 HttpModule,HttpHandler的处理,前者HttpModule用于页面处理前和处理后的一些事件的处理,后者HttpHandler进行真正的页面处理。
针对水印的全局实现
Default.aspx页面代码:
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:Image ID="Image1" runat="server" ImageUrl="~/ProductImgs/1.jpg" />
- <asp:Image ID="Image2" runat="server" ImageUrl="~/ProductImgs/2.jpg" />
- <asp:Image ID="Image3" runat="server" ImageUrl="~/ProductImgs/3.jpg" />
- <asp:Image ID="Image4" runat="server" ImageUrl="~/ProductImgs/4.jpg" />
- <asp:Image ID="Image5" runat="server" ImageUrl="~/ProductImgs/default.jpg" />
- </div>
- </form>
- </body>
Handler1.ashx页面:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.IO;
- using System.Drawing;
- using System.Drawing.Imaging;
- namespace WebApplication1
- {
- /// <summary>
- /// Handler1 的摘要说明
- /// </summary>
- public class Handler1 : IHttpHandler
- {
- private string IMGS = "/~ProductImgs/";
- public void ProcessRequest(HttpContext context)
- {
- Image img;
- string path = context.Request.PhysicalPath;
- if (File.Exists(path))
- {
- img=Image.FromFile(path);
- Graphics graphics = Graphics.FromImage(img);
- graphics.DrawString("版权所有",new Font("宋体",20),Brushes.Red,img.Width-50,img.Height-20);
- graphics.Dispose();
- }
- else
- {
- img = null;
- }
- context.Request.ContentType = "image/jpeg";
- img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
- img.Dispose();
- context.Response.End();
- }
- public bool IsReusable
- {
- get
- {
- return false;
- }
- }
- }
- }