zoukankan      html  css  js  c++  java
  • 使用HttpHandler实现图片防盗链

    NOTE:这个例子来自于《Maximizing ASP.NET Real World, Object-Oriented Development》一书:

    Step.1:创建文件 CustomHandler.cs,代码如下:

    using System;
    using System.Web;

    namespace CustomHandler{
        public class JpgHandler : IHttpHandler{
           public void ProcessRequest(HttpContext context){
               // 获取文件服务器端物理路径
               string FileName = context.Server.MapPath(context.Request.FilePath);
               // 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片
               if (context.Request.UrlReferrer.Host == null){
                  context.Response.ContentType = "image/JPEG";
                  context.Response.WriteFile("/error.jpg");
               }else{
                  // 如果 UrlReferrer中不包含自己站点主机域名,则显示一张默认的禁止盗链的图片
                 if (context.Request.UrlReferrer.Host.IndexOf("yourdomain.com") > 0){
                      context.Response.ContentType = "image/JPEG";
                      context.Response.WriteFile(FileName);
                  }else{
                      context.Response.ContentType = "image/JPEG";
                      context.Response.WriteFile("/error.jpg");
                  }
               }
           }

           public bool IsReusable{
               get{ return true; }
           }
        }
    }

    Step.2 编译这个文件

    csc /t:library /r:System.Web.dll CustomHandler.cs

    Step.3 将编译好的 CustomHandler.dll 拷贝到站点的 Bin 目录下。

    Step.4 在Web.Config 中注册这个Handler。

    <system.web>
        <httpHandlers>
          <add path="*.jpg" verb="*" type="CustomHandler.JpgHandler, CustomHandler" />
        </httpHandlers>
    </system.web>

    OK,诸位可以按步骤自行测试一下,这里就不赘述了。
  • 相关阅读:
    三(奇数)等分两者中间有间隔,两端没间隔
    网易云音乐基于 Flink + Kafka 的实时数仓建设实践
    【电商知识】关于电商定价的几个策略
    硬核!15张图解Redis为什么这么快
    用户画像实践:神策标签生产引擎架构
    数据产品实战(二):ABTest平台
    R代码|基于特征重要性的特征排序代码
    R代码|K均值算法R语言代码
    一文了解R语言数据分析 ----主成分分析
    全网最全 | MySQL EXPLAIN 完全解读
  • 原文地址:https://www.cnblogs.com/top5/p/1598869.html
Copyright © 2011-2022 走看看