图片防盗链

新建一个类库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 >

你可能感兴趣的:(server,null)