新建ASP.NET Web应用程序WebDAOLIAN1和WebDAOLIAN2
然后在WebDAOLIAN1里面新建一个images文件夹存储图片 再新建一个PreventLink类用来编写HttpHandler 代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebDAOLIAN1
{
public class PreventLink : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
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 errorlmagePath = context.Request.PhysicalApplicationPath + "images/download.jpg";
//发送至客户端
context.Response.WriteFile(errorlmagePath);
}
else
{
context.Response.WriteFile(context.Request.PhysicalPath);
}
}
}
}
然后在WebDAOLIAN1新建一个web窗体Index1 然后在Index1窗体下编写以下代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index1.aspx.cs" Inherits="WebDAOLIAN.Index1" %>
<!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="images/001.jpg" />
<img src="images/002.jpg" />
<img src="images/003.jpg" />
</div>
</form>
</body>
</html>
然后在WebDAOLIAN1里面的Web.config里面的configuration里面加上以下代码
<system.webServer>
<handlers>
<add verb="*" path="images/*" type="WebDAOLIAN1.PreventLink" name="pink" />
</handlers>
</system.webServer>
然后我们在WebDAOLIAN2新建一个web窗体Index2 然后编写以下代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index2.aspx.cs" Inherits="WebDAOLIAN2.Index1" %>
<!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>
<p>此图片来自第一个站点</p>
<img src="https://localhost:44305/images/001.jpg" />
<img src="https://localhost:44305/images/002.jpg" />
<img src="https://localhost:44305/images/003.jpg" />
</div>
</form>
</body>
</html>
然后运行 index1如下
Index2如下