HttpHandler对象实现防盗链

新建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如下

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值