ASP.net 使用HttpHandler实现图片防盗链

首先是HttpHandler类的代码:

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

namespace HttpHandler
{
    public class JPEGHandler : IHttpHandler
    {
        #region IHttpHandler 成员

     public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string fileName = context.Request.FilePath;

            if (context.Request.UrlReferrer.Host == null)
            {
                context.Response.ContentType = "image/JPEG";
                context.Response.WriteFile("/no.jpg");
            }
            else
            {
                if (context.Request.UrlReferrer.Host.IndexOf("localhost") >= 0)
                {
                    context.Response.ContentType = "image/JPEG";
                    context.Response.WriteFile(fileName);
                }
                else
                {
                    context.Response.ContentType = "image/JPEG";
                    context.Response.WriteFile("/no.jpg");
                }
            }
        }

        #endregion
    }
}

然后是web.config中的代码:

<configuration>
	<system.web>
		<httpHandlers>
			<add verb="*" path="*.jpg" type="HttpHandler.JPEGHandler"/>
		</httpHandlers>
</configuration>
最后就是在网站根目录下放入no.jpg就可以了。
posted @ 2010-07-10 10:13  refuly  阅读(473)  评论(0编辑  收藏  举报