我们都知道HttpHanler是处理用户请求的,那么我们当然也可以自己注册一个HttpHandler来处理我们请求
这里我们就做一个专门处理图片的HttpHandler 【当用户请求的页面含有jpg的图片的时候,必然就会调用我们的自定义的Handler来处理,前提是我们需要在web.config中配置注册我们自定义HttpHandler】
第一步:创建一个WebForm项目
第二步:在项目中添加一个MyHandler的类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1
{
public class MyHandler:IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
//判断是否是本地网站引用图片,如果是则返回正确的图片
if (context.Request.UrlReferrer.Host == "localhost")
{
//设置客户端缓冲时间过期时间为0,即立即过期
context.Response.Expires = 0;
//清空服务器端为此会话开启的输出缓存
//context.Response.Clear();
//设置输出文件类型
context.Response.ContentType = "image/jpg";
//将请求文件写入到输出缓存中
context.Response.WriteFile(context.Request.PhysicalPath);
//将输出缓存中的信息传送到客户端
context.Response.End();
}
//如果不是本地引用,则是盗链本站图片
else
{
//设置客户端缓冲时间过期时间为0,即立即过期
context.Response.Expires = 0;
//清空服务器端为此会话开启的输出缓存
context.Response.Clear();
//设置输出文件类型
context.Response.ContentType = "image/jpg";
//将请求文件写入到输出缓存中
context.Response.WriteFile(context.Request.PhysicalApplicationPath + "images/wowo.jpg");
//将输出缓存中的信息传送到客户端
context.Response.End();
}
}
}
}
第三步:在Web.config文件中对这个自定义的MyHandler进行注册
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<!--<httpHandlers>
<add path="*.jpeg" verb="*" type="WebApplication1.MyHandler.cs,WebApplication1" />
</httpHandlers>-->
</system.web>
<system.webServer>
<handlers>
<!--注册我们自定义专门处理后缀名为jpg的Handler-->
<add name="MyHandler" path="*.jpg" verb="*" type="WebApplication1.MyHandler,WebApplication1"/>
</handlers>
</system.webServer>
</configuration>
第四部:调用(在项目中添加一个WebForm1.aspx页面,在里面也放了一个图片,当加载这个图片的时候,就会向服务器发起对这个图片的请求,然后就会进入到我们自定义对jpg图片的请求的Handler中,对这个图片进行相应的处理)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
我是一个IDV
</div>
<%--执行到这段代码的时候,就是向服务器请求这个图片,于是就会调用我们自己注册的MyHandler来处理这个图片请求--%>
<img src="../Images/leijun.jpg" />
</div>
</form>
</body>
</html>