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();
        }
    }
}
复制代码

 

本文转自ylbtech博客园博客,原文链接:http://www.cnblogs.com/ylbtech/archive/2013/02/16/2878661.html ,如需转载请自行联系原作者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值