zoukankan      html  css  js  c++  java
  • ASP.NET实现图片防盗链

    使用httpHandle来实现,对图片文件的请求做专门的处理
    第一步:创建一个类,继承自IHttpHandler,代码如下

    C# code

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

    }

    }

    }

     



    第二步:编译成DLL
    csc /t:library CustomHandler.cs
    第三步:添加编译好的DLL引用到当前站点的bin文件夹下
    第四步:在Web.Config 中注册这个Handler

    C# code

    <system.web>

    <httpHandlers>

    <add path="*.jpg,*.jpeg,*.gif,*.png,*.bmp" verb="*" type="CustomHandler.JpgHandler,CustomHandler" />

    </httpHandlers>

    </system.web>

     


    //verb
    指的是请求此文件的方式,可以是postget,用*代表所有访问方式。CustomHandler.JpgHandler表示命名空间和类名,CustomHandler表示程序集名。

  • 相关阅读:
    Yii together
    linux 文件处理大杂烩
    Ubuntu 17.10 环境初始化
    关掉 ubuntu bug 报告功能
    git svn 流程
    [Mac] How do I move a window whose title bar is off-screen?
    可爱的Python_课后习题_CDay−5 Python 初体验和原始需求
    python_编程规范
    python_excel
    python_os
  • 原文地址:https://www.cnblogs.com/ghfsusan/p/1964579.html
Copyright © 2011-2022 走看看