防盗链

 1 /// <summary>
 2      /// 图片防盗链
 3      /// </summary>
 4      public class ImgHandler : IHttpHandler
 5      {
 6          const string errImg = "/Content/daolian.jpg";
 7          public void ProcessRequest(HttpContext context)
 8          {
 9              // 获取文件服务器端物理路径
10              string FileName = context.Server.MapPath(context.Request.FilePath);
11              // 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片
12              if (context.Request.UrlReferrer == null || context.Request.UrlReferrer.Host == null)
13              {
14                  context.Response.ContentType = "image/JPEG";
15                  context.Response.WriteFile(errImg);
16              }
17              else
18              {
19                  if (context.Request.UrlReferrer.Host.IndexOf("eee114.com") > 0)
20                  {
21                      context.Response.ContentType = "image/JPEG";
22                      context.Response.WriteFile(FileName);
23                  }
24                  else
25                  {
26                      context.Response.ContentType = "image/JPEG";
27                      context.Response.WriteFile(errImg);
28                  }
29              }
30          }
31  
32          public bool IsReusable
33          {
34              get { return true; }
35          }
36      }

在web.config中的<system.web>节点去调用它

   <!-- HttpHandlers对请求的扩展名进行处理 -->
    <httpHandlers>
      <add path="*.jpg,*.jpeg,*.gif,*.png,*.bmp" verb="*" type="HttpHandler.ImgHandler,HttpHandler" />
    </httpHandlers>
posted @ 2013-02-09 17:10  tinaleft  阅读(231)  评论(0编辑  收藏  举报