图片防盗链

虽然这个很多人有讲到了,一搜一大把!现在写主要是以后要用不用在去找了

新建一个类库AvoidImage 继承IHttpHandler,记得引用System.Web

 

class AvoidImage : IHttpHandler
    {

        
#region IHttpHandler 成员

        
public bool IsReusable
        {
            
//get { throw new NotImplementedException(); }
            get {
                
return true;
            }
        }

        
#endregion
        
public void ProcessRequest(HttpContext context)
        {
            Uri urlreferrer 
= context.Request.UrlReferrer;//访问来源地址
            string ip = context.Request.UserHostAddress;//访问来源Ip地址
            string serverhost = context.Request.Url.Host;//当前访问主机地址
            string localIp = ConfigurationManager.AppSettings["LocalIP"];
            
if (urlreferrer == null || urlreferrer.Host.ToLower() != serverhost.ToLower() || ip != localIp)
            {
                context.Response.WriteFile(
"~/images/index_adr11.gif");
            }
            
else
            {
                context.Response.WriteFile(context.Request.PhysicalPath);
            }
        }
    }

 

 

default.aspx

 

<body>
    
<form id="form1" runat="server">
    
<div>
    
<img src="images/Advertise_1.jpg" />
    
</div>
    
</form>
</body>

 

 

这样当主机头不对或ip不对就看不到那张图片,显示的是我们的默认图,下载下来也是默认图片

来自http://www.cnblogs.com/cyq1162/archive/2010/08/26/1809169.html

posted @ 2010-09-06 10:00  蓝丶 sky  阅读(463)  评论(5编辑  收藏  举报