zoukankan      html  css  js  c++  java
  • 图片防盗链之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>
  • 相关阅读:
    Python运算符及逻辑运算
    Python编码、流程控制、格式化输出
    Docker私有仓库Harbor部署与使用
    react
    理事会
    关于elementui form表单过长,看不到未填项
    js
    vue 父子传值
    养生
    html知识点
  • 原文地址:https://www.cnblogs.com/dodui/p/1828490.html
Copyright © 2011-2022 走看看