NOTE:如果你新建一个项目,并且在项目下创建HandlerTest.cs,然后让站点引用该项目,那么在生成解决方案的时候会自动将编译好的.dll文件添到Bin目录中。
NOTE:MyDll只写程序集名,不要加后面的.dll。
使用HttpHandler实现图片防盗链
有了之前这么多的准备知识,实现现在的目标就容易得多了:
NOTE:这个例子,以及下面的一个例子均来自于《Maximizing ASP.NET Real World, Object-Oriented Development》一书:
Step.1:创建文件 CustomHandler.cs,代码如下:
using System;
using System.Web;
namespace CustomHandler{
public class JpgHandler : IHttpHandler{
public void ProcessRequest(HttpContext context){
// 获取文件服务器端物理路径
string FileName = context.Server.MapPath(context.Request.FilePath);
// 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片
if (context.Request.UrlReferrer.Host == null){
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}else{
// 如果 UrlReferrer中不包含自己站点主机域名,则显示一张默认的禁止盗链的图片
if (context.Request.UrlReferrer.Host.IndexOf("yourdomain.com") > 0){
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(FileName);
}else{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}
}
}
public bool IsReusable{
get{ return true; }
}
}
}
Step.2 编译这个文件
csc /t:library /r:System.Web.dll CustomHandler.cs
Step.3 将编译好的 CustomHandler.dll 拷贝到站点的 Bin 目录下。
Step.4 在Web.Config 中注册这个Handler。
<system.web>
<httpHandlers>
<add path="*.jpg" verb="*" type="CustomHandler.JpgHandler, CustomHandler" />
</httpHandlers>
</system.web>
OK,诸位可以按步骤自行测试一下,这里就不赘述了。
通过IhttpHandler实现图片验证码
也可以在一个.ashx文件中实现IHttpHandler,而不是采用这种提前编译的方式。
Step.1 打开Vs2005,“添加新项”,“一般处理程序”。新建文件后,VS会自动在文件中添加如下的代码:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable {
get {
return false;
}
}
}
Step.2 将代码改写成如下所示:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Web;
using System.Web.SessionState;
public class Handler : IHttpHandler, IRequiresSessionState {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "image/gif";
//建立Bitmap对象,绘图
Bitmap basemap = new Bitmap(200, 60);
Graphics graph = Graphics.FromImage(basemap);
graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
Random r = new Random();
string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
string letter;
StringBuilder s = new StringBuilder();
//添加随机的五个字母
for (int x = 0; x < 5; x++) {
letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
s.Append(letter);
graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
}
//混淆背景
Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
for (int x = 0; x < 6; x++)
graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
//将图片保存到输出流中
basemap.Save(context.Response.OutputStream, ImageFormat.Gif);
context.Session["CheckCode"] = s.ToString(); //如果没有实现IRequiresSessionState,则这里会出错,也无法生成图片
context.Response.End();
}
public bool IsReusable {
get { return true; }
}
}
需要特别注意的是,Handler类不仅需要实现 IHttpHandler接口(这个显然),为了在这个Handler类中使用SessionState,还需要实现IRequiresSessionState接口,对于这个接口,MSDN的解释是这样的:Specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.(翻译过来是:指定当前Http Handler需要对SessionState值的读写访问权。这是一个标记接口,没有任何方法)。