转: Asp.Net:IHttpHandler防止图片盗链

本文地址:http://www.cnblogs.com/yizhyi/admin/javascript:;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Globalization;
using System.IO;
namespace HttpHandler
{
    public class ImageHandler:IHttpHandler
    {
        #region IHttpHandler 成员
        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            string IMG_path = req.PhysicalPath;
            string contentType;
            if (req.UrlReferrer != null && req.UrlReferrer.Host.Length > 0)
            {
                if (CultureInfo.InvariantCulture.CompareInfo.Compare(req.Url.Host, req.UrlReferrer.Host, CompareOptions.IgnoreCase) != 0)
                {
                    IMG_path = context.Server.MapPath("~/images/error.gif");
                }
                contentType = GetContentType(IMG_path);
                if (File.Exists(IMG_path))
                {
                    context.Response.StatusCode = 200;
                    context.Response.ContentType = contentType;
                    context.Response.WriteFile(IMG_path);
                }
                else
                {
                    context.Response.StatusCode = 404;
                    context.Response.Status = "无法找到你请求的文件";
                }
            }
        }
        public bool IsReusable
        {
            get { return true; }
        }
        #endregion
        private string GetContentType(string path)
        {
            string extension = Path.GetExtension(path);
            string type;
            switch (extension)
            {
                case ".gif":
                    type = "image/gif";
                    break;
                case ".jpg":
                    type = "image/Jpeg";
                    break;
                case ".png":
                    type = "image/png";
                    break;
                default:
                    type = "";
                    break;
            }
            return type;
        }
    }
}


web.config
          <add verb="*" path="*.jpg" type="HttpHandler.ImageHandler, HttpHandler"/>
            <add verb="*" path="*.gif" type="HttpHandler.ImageHandler, HttpHandler"/>
            <add verb="*" path="*.png" type="HttpHandler.ImageHandler, HttpHandler"/>

转载于:https://www.cnblogs.com/yizhyi/archive/2009/03/13/1410330.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值