首页 > 代码库 > HttpHandler实现网页图片防盗链

HttpHandler实现网页图片防盗链

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5  
 6 /// <summary>
 7 /// HotLinkedHandler 的摘要说明
 8 ///1.后台代码
 9 /// </summary>
10 public class HotLinkedHandler:IHttpHandler
11 {
12  
13 public bool IsReusable
14 {
15 get { return false; }
16 }
17  
18 public void ProcessRequest(HttpContext context)
19 {
20 //得到默认图片
21 string defaultImg = context.Server.MapPath("~/images/BookCovers/default.jpg");
22 //得到图片路径
23 string bookImg = context.Request.PhysicalPath;
24  
25 if (context.Request.UrlReferrer.Host == "location" && context.Request.UrlReferrer.Port == context.Request.Url.Port)
26 {
27 context.Response.WriteFile(bookImg);
28 }
29 else {
30 context.Response.WriteFile(defaultImg);
31 }
32  
33 context.Response.End();
34 }
35 }

 

 
在web.config中进行配置
1 <system.webServer>
2 <!--path:图片路径,type:指定处理程序类,verb:谓词 get post ftp等 *匹配所有,name:名称-->
3 <handlers>
4 <!--配置防盗链-->
5 <add type="HotLinkedHandler" path="images/BookCovers/*.jpg" name="hotLinked" verb="*"/>
6 </handlers>
7 </system.webServer>

 

 
 
 
 
//2.前台代码
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestWaterImgSecound.aspx.cs" Inherits="TestWaterImg" %>
 2  
 3 <!DOCTYPE html>
 4  
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 8 <title></title>
 9 </head>
10 <body>
11 <form id="form1" runat="server">
12 <div>
13 <img src=http://www.mamicode.com/"images/BookCovers/7111171144.jpg" /><img src=http://www.mamicode.com/"images/BookCovers/7113054846.jpg" />
14 </div>
15 </form>
16 </body>
17 </html>

 

 
 
 
//3.另一个网站引用图片路径
 
 1 <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
 2  
 3 <!DOCTYPE html>
 4  
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 8 <title></title>
 9 </head>
10 <body>
11 <form id="form1" runat="server">
12 <div>
13 <img src=http://www.mamicode.com/"http://localhost:22247/images/BookCovers/7111171144.jpg" />
14 </div>
15 </form>
16  
17 </body>
18 </html>

 

 

HttpHandler实现网页图片防盗链