简易防盗链

防盗链

防盗链是Web项目开发过程中必定会用到的技术,否则网站资源会被其他网站引用,并造成损失

实现方法

创建两个网站

首先需要创建两个web项目,并且分别在不同的项目下建立一个web窗体
在这里插入图片描述
窗体一的代码 img中填入图片的代码

 <img src="img/1.jpg" alt="Alternate Text" />
            <img src="img/2.jpg" alt="Alternate Text" />
            <img src="img/3.jpg" alt="Alternate Text" />

效果图如下
在这里插入图片描述
窗体二代码如下
其中https://localhost:44351/img/2.jpg为窗体一图片的图片地址

 <p>以下图片来自第一个网站</p>
            <img src="https://localhost:44351/img/1.jpg" alt="Alternate Text" />
            <img src="https://localhost:44351/img/2.jpg" alt="Alternate Text" />
            <img src="https://localhost:44351/img/3.jpg" alt="Alternate Text" />

效果图如下
在这里插入图片描述

编写类

在第一个web项目中创建一个PreventLink类

代码为

 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 + "img/bofang.png";
                //发送至客户端
                context.Response.WriteFile(errorlmagePath);
            }
            else
            {
                context.Response.WriteFile(context.Request.PhysicalPath);
            }
        }

在窗体一中的Web.config写入

<system.webServer>
    <handlers>
      <add verb="*" path="img/*.*" type="WebApplication3.PreventLink" name="plink"/>
    </handlers>
  </system.webServer>

然后在解决方案中点击属性设置
在这里插入图片描述

然后点击运行窗体二会显示
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值