HttpHandler实现网页图片防盗链

时间:2022-09-20 22:58:29
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; /// <summary>
/// HotLinkedHandler 的摘要说明
///1.后台代码
/// </summary>
public class HotLinkedHandler:IHttpHandler
{ public bool IsReusable
{
get { return false; }
} public void ProcessRequest(HttpContext context)
{
//得到默认图片
string defaultImg = context.Server.MapPath("~/images/BookCovers/default.jpg");
//得到图片路径
string bookImg = context.Request.PhysicalPath; if (context.Request.UrlReferrer.Host == "location" && context.Request.UrlReferrer.Port == context.Request.Url.Port)
{
context.Response.WriteFile(bookImg);
}
else {
context.Response.WriteFile(defaultImg);
} context.Response.End();
}
}
 
在web.config中进行配置
 <system.webServer>
<!--path:图片路径,type:指定处理程序类,verb:谓词 get post ftp等 *匹配所有,name:名称-->
<handlers>
<!--配置防盗链-->
<add type="HotLinkedHandler" path="images/BookCovers/*.jpg" name="hotLinked" verb="*"/>
</handlers>
</system.webServer>
 
 
 
 
//2.前台代码
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestWaterImgSecound.aspx.cs" Inherits="TestWaterImg" %>

 <!DOCTYPE html>

 <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>
<img src="data:images/BookCovers/7111171144.jpg" /><img src="data:images/BookCovers/7113054846.jpg" />
</div>
</form>
</body>
</html>
 
 
 
//3.另一个网站引用图片路径
 
 <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

 <!DOCTYPE html>

 <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>
<img src="http://localhost:22247/images/BookCovers/7111171144.jpg" />
</div>
</form> </body>
</html>