隐藏

Asp.net防止图片盗链

发布:2020/1/2 17:24:52作者:管理员 来源:本站 浏览次数:1093

public class LinkProtectHandler: IHttpHandler
    {
        #region IHttpHandler 成员
 
        public bool IsReusable
        {
            get {return true; }
        }
 
        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("/LinkProtect.jpg");
            }
            else
            {
                //如果UrlReferrer中不包含自己站点的主机域名,则显示一张默认的禁止盗链图片
                if (context.Request.UrlReferrer.Host.IndexOf("XXX.com")>0)
                {
                    context.Response.ContentType = "image/JPEG";
                    context.Response.WriteFile(fileName);
                }
                else
                {
                    context.Response.ContentType = "image/JPEG";
                    context.Response.WriteFile("/LinkProtect.jpg");
                }
            }
        }
 
        #endregion
    }
 
 
 
 
Web.Config里面注册如下:
<add verb="*" path="*.jpg" type="WebTest.LinkHandler,WebTest"/>