接口IHttpHandler的定義如下:
復(fù)制代碼 代碼如下:
interface IHttpHandler
{
void ProcessRequest(HttpContext ctx);
bool IsReuseable { get; }
1新建一網(wǎng)站,名為MyHttpHandlerTest
2右擊添加,選擇類庫(kù),取名為MyHttpHandler
3-在上一步新建的類庫(kù)上右鍵添加System.Web引用
主要代碼:
復(fù)制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.SessionState;
namespace MyHttpHandler
{
public class Class1:IHttpHandler,IRequiresSessionState
{
#region IHttpHandler成員
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Write("handler處理");
}
#endregion
}
}
4-在MyHttpHandler類庫(kù)上右鍵,生成,取名為MyHttpHandler
5-在web.config中的system.web節(jié)點(diǎn)中天下如下節(jié)點(diǎn)
httpHandlers>
add verb="*" path="Handler1.aspx" type="MyHttpHandler.Class1,MyHttpHandler"/>
!--
配置文件中的選項(xiàng)說(shuō)明:
· verb可以是"GET"或"POST",表示對(duì)GET或POST的請(qǐng)求進(jìn)行處理。"*"表示對(duì)所有請(qǐng)求進(jìn)行處理。
· Path指明對(duì)相應(yīng)的文件進(jìn)行處理,"*.aspx"表示對(duì)發(fā)給所有ASPX頁(yè)面的請(qǐng)求進(jìn)行處理??梢灾该髀窂?,如"/test/*.aspx",表明只對(duì)test目錄下的ASPX文件進(jìn)行處理。
· Type屬性中,逗號(hào)前的字符串指明HttpHandler的實(shí)現(xiàn)類的類名,后面的字符串指明Dll文件的名稱。
格式如:type="自定義HttpHandler的實(shí)現(xiàn)類的全名,自定義HttpHandler的實(shí)現(xiàn)類的命名空間(即Dll名)"
或 type="自定義HttpHandler的實(shí)現(xiàn)類的全名"
-->
/httpHandlers>
6-在MyHttpHandlerTest右鍵添加引用,選擇項(xiàng)目找到剛才編譯后的.dll文件
7-運(yùn)行Handler1.aspx,頁(yè)面顯示:
![](/d/20211017/169150a0646a7d218d68da11f4e5c475.gif)
下面我們利用HttpHandler將一段文字生成于圖片中
添加一個(gè)類,默認(rèn)為Class.cs
復(fù)制代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
/// summary>
/// Class1 的摘要說(shuō)明
/// /summary>
public class Class1:IHttpHandler
{
public Class1()
{
//
// TODO: 在此處添加構(gòu)造函數(shù)邏輯
//
}
public bool IsReusable
{
get { return true; }
}
private static Image OldImage = null;
private static Image GetOldImage(HttpContext context)
{
if (OldImage == null)
{
OldImage = Image.FromFile(context.Server.MapPath("~/Images/Old.jpg"));
}
return OldImage.Clone() as Image;
}
public void ProcessRequest(HttpContext context)
{
Image newimage = GetOldImage(context);
Graphics gh = Graphics.FromImage(newimage);
Font font = new Font("Monaco", 24.0f, FontStyle.Regular);
string writetext = HttpUtility.UrlEncode(context.Request.QueryString["writetext"]);
gh.DrawString(HttpUtility.UrlDecode(writetext), font, new SolidBrush(Color.LightBlue), 20.0f, newimage.Height - font.Height - 30);
newimage.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
gh.Dispose();
newimage.Dispose();
}
}
新建一個(gè).aspx頁(yè)面,添加一個(gè)HyperLink控件,再在其.cs文件中添加一段代碼傳值
復(fù)制代碼 代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
HyperLink1.NavigateUrl = "img.jpg?writetext=" + HttpUtility.UrlEncode("大蝸牛");
}
另外還需在web.config文件中將httpHandlers節(jié)點(diǎn)中改為如下
add verb="*" path="*.jpg" type="Class1"/>
表明對(duì)所有的.jpg格式的文件才會(huì)處理
參考《道不遠(yuǎn)人 深入解析asp.net 2.0控件開發(fā)》