ImageProtect(图片防盗链)

1,ImageProtect.cs

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



//<system.web>
//      <httpHandlers>
//        <add verb="*" path="Download/*.jpg" type="ImageProtect"/>
//      </httpHandlers>
//    </system.web>

/// <summary>
///ImageProtect 的摘要说明
/// </summary>
public class ImageProtect:IHttpHandler
{
    public ImageProtect()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }



    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        //判断是否本地引用,如果是则返回给客户端正确的图片
        if (context.Request.UrlReferrer.Host == "image.eduask.com" && context.Request.UrlReferrer.Port == 80)
        {
            //设置客户端缓冲文件过期时间为0,即立即过期
            context.Response.Expires = 0;
            //清空服务器端为此会话开辟输出的缓存
            context.Response.Clear();
            //获得文件类型
            context.Response.ContentType = "image/jpeg";
            //将请求的文件写入服务器端为此会话开辟输出缓存中
            context.Response.WriteFile(context.Request.PhysicalPath);
            //将服务器端为此会话开辟的输出缓存中的信息返回客户端
            context.Response.End();

        }
        //如果不是否本地引用,则属于盗连引用,返回给客户端错误的图片
        else
        {
            //设置客户端缓冲文件过期时间为0,即立即过期
            context.Response.Expires = 0;
            //清空服务器端为此会话开辟输出的缓存
            context.Response.Clear();
            //获得文件类型
            context.Response.ContentType = "image/jpeg";
            //将特殊的报告错误的图片文件写入到服务器端为此会话开辟输出缓存中
            context.Response.WriteFile("~/images/error.jpg");
            //将服务器端为此会话开辟的输出缓存中的信息返回客户端
            context.Response.End();
        }
    }
}
原文地址:https://www.cnblogs.com/ylbtech/p/2878661.html