防盗链可以有效的防止一些不良网站盗取我们的的网站资源
防盗链演示与防盗链操作:
1.创建一个网站,在网站下创建Images里面放入图片,在这个网站中,图片可以正常的显示出来
2.创建第二个网站,这个网站引用第一个网站图片的链接,结果不能正常显示图片,而是显示错误的图片。
在第一个页面中插入图片
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="first.aspx.cs" Inherits="_2021_05_31.first" %>
<!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>
<style>
.image {
width:625px;
height:500px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
//插入图片
<asp:Image ID="Image1" runat="server" src="images/mofang.jpg" CssClass="image" />
<asp:Image ID="Image2" runat="server" src="images/IU.jpg" CssClass="image" />
<asp:Image ID="Image3" runat="server" src="images/lang.jpg" CssClass="image" />
</div>
</form>
</body>
</html>
效果展示:
第二步创建盗链网站:添加aspx,引用第一个网站提供的三幅图片
在盗链网站图片路径中插入我们复制过来的图片链接
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_2021_05_31_2_.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>
<style>
.image {
width:625px;
height:500px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>以下图片资源来自第一个站点</p>
//图片路径来源于第一个站点图片路径
<asp:Image ID="Image1" runat="server" src="http://localhost:49446/images/mofang.jpg" CssClass="image" />
<asp:Image ID="Image2" runat="server" src="http://localhost:49446/images/IU.jpg" CssClass="image" />
<asp:Image ID="Image3" runat="server" src="http://localhost:49446/images/lang.jpg" CssClass="image" />
</div>
</form>
</body>
</html>
效果展示:
显而易见第二个网站盗取了第一个网站的图片资源,下面通过HttpHandler解决盗链
在第一个网站中添加一个HttpHandler类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace _2021_05_31
{
public class HttpHandler : IHttpHandler
{
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
//获取上次请求的URL
Uri lastUrl = context.Request.UrlReferrer;
//获取本次请求的URL
Uri currentUrl = context.Request.Url;
//判断是否为盗链
if (lastUrl.Host != currentUrl.Host || lastUrl.Port != currentUrl.Port)
{
//获取“请勿盗链”警示提示图片路径
string errorImagePath = context.Request.PhysicalApplicationPath + "image/lanping.jpg";
//发送至客户端
context.Response.WriteFile(errorImagePath);
}
else
{
context.Response.WriteFile(context.Request.PhysicalPath);
}
}
}
}
在Web.config中配置实现当请求images文件夹中的JPG图片时,由HttpHandle类处理
在<configuration>中添加:
<system.webServer>
<handlers>
//解决方案名称.类名
<add verb="*" path="images/*" type="_2021_05_31.HttpHandler" name="plink" />
</handlers>
</system.webServer>
第三步访问第二个网站页面的效果:
加载出来的页面并不是显示之前的三张图片,而是显示了我们准备的错误的图片
防盗链技术是Web项目开发过程中必定会用到的技术,否则网站资源会被其他网站引用,盗链一方面损害了原网站的合法利益,另一方面又加重了服务器的负担,所以防盗链技术是一定要掌握的。