• 图片防盗链之HttpHandler方法实现


    图片防盗链之HttpHandler方法实现


    在网上搜索到了的答案都极其珍贵,这次,是关于.NET应用相关的,需要对图片相关文件进行防盗链,而又没有相关服务器的权限,不过幸好.net的功能很强大,足以满足各种需求了。

    以下是摘抄了,基本上可以直接使用形的。


    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; }
           }
        }
    }


    2 编译这个文件

    引用内容 引用内容
    csc /t:library /r:System.Web.DLL CustomHandler.cs


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

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


    <system.web>
        <httpHandlers>
          <add path="*.jpg" verb="*" type="CustomHandler.JpgHandler, CustomHandler" />
        </httpHandlers>
    </system.web>
  • 相关阅读:
    SpringBoot2.x 工作流开源项目
    Nginx:终于有人把 Nginx 说清楚了,图文详解!
    MySQL8配置修改:Mysql group by this is incompatible with sql_mode=only_full_group_by
    解决错误:java.sql.SQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"
    工作时使用的vim配置
    工作笔记整理
    Linux mint启用内核转储
    usleep和sleep
    gdb使用
    掩码配置为255.255.255.255
  • 原文地址:https://www.cnblogs.com/dodui/p/1828490.html
Copyright © 2020-2023  润新知