ASP.NET防止自己网站的资源被盗(通过IHttpHandler 带样例说明)

我这里用的图片被盗举例子

一个正常的网页

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StolenDemo.aspx.cs" Inherits="Stolen.StolenDemo" %>

<!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/adv1.jpg" /><img src="Images/adv2.jpg" /><img src="Images/adv3.jpg" />
        </div>
    </form>
</body>
</html>

模拟一个盗用网站的网页
localhost是我另一个项目的,这里服务器不方便弄,就直接新建项目

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StealDemo.aspx.cs" Inherits="steal.StealDemo" %>

<!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="https://localhost:44353/Images/adv1.jpg" />
              <img src="https://localhost:44353/Images/adv2.jpg" />
              <img src="https://localhost:44353/Images/adv3.jpg" />
        </div>
    </form>
</body>
</html>

没有任何防盗的操作效果图,

在这里插入图片描述
防盗措施:

建一个类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Stolen
{
    public class prevention : IHttpHandler
    {
        public bool IsReusable =>true;

        public void ProcessRequest(HttpContext context)
        {
            //上一次的uri与这一次的Uri看看是不是host和port是不是相同,如果不相同说明是被盗了
            Uri pre = context.Request.UrlReferrer;
            Uri cur = context.Request.Url;
            if (pre.Host != cur.Host || pre.Port != cur.Port)
            {
                string errorPath=context.Request.PhysicalApplicationPath+ "Error/default.jpg";
                context.Response.WriteFile(errorPath);
            }
            else
            {
                context.Response.WriteFile(context.Request.PhysicalPath);
            }
        }
    }
}

找到配置文件添加代码
在这里插入图片描述
path是防盗的范围,type是那个类的路径:

也就是命名空间 .(点)类名

<system.webServer>
    <handlers>
      <add verb="*" name="preventLink" path="Images/*.jpg" type="Stolen.prevention"/>
    </handlers>
  </system.webServer>

效果图
找不到的那个图片,图片无法显示的那个,是一张图片,我在类里面改的,如果是盗取的话,就给他一个找不到的图片
在这里插入图片描述

发布了1857 篇原创文章 · 获赞 3万+ · 访问量 576万+

猜你喜欢

转载自blog.csdn.net/a1439775520/article/details/105737938