ASP.NET简单实现图片防盗链

来源:互联网 发布:淘宝客服聊天用语 编辑:程序博客网 时间:2024/06/10 17:04

原理很简单,就是对请求的文件进行判断,若图片请求的URL地址上不是我们自己网站上的域名,则说明图片被盗链了,此时就可以用一张特定的版权图片进行替换,以保护自己站点的资源不被随意引用。

首先,需要在Global.asax中

void Application_BeginRequest(object sender, EventArgs e){  new ProcessRequestHelper().ProcessRequest();}

其次,在特定的封装类中进行请求判断操作:

public class ProcessRequestHelper{    public ProcessRequestHelper()    {        //        //TODO: 在此处添加构造函数逻辑        //    }    public void ProcessRequest()    {        string FileName = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.FilePath);        string strImgEnd=HttpContext.Current.Request.Url.AbsolutePath.ToString().ToLower();        if (strImgEnd.EndsWith(".jpg") || strImgEnd.EndsWith(".gif") || strImgEnd.EndsWith(".png") || strImgEnd.EndsWith(".bmp") || strImgEnd.EndsWith(".jpeg"))        {            try            {                if (HttpContext.Current.Request.UrlReferrer.Host != SystemHelper.SiteURL.Trim())                {                    if (HttpContext.Current.Request.UrlReferrer.Host == null)                    {                        HttpContext.Current.Response.ContentType = "image/JPEG";                        HttpContext.Current.Response.WriteFile("~/Image/forbid.png");                    }                    else                    {                        if (HttpContext.Current.Request.UrlReferrer.Host.IndexOf(SystemHelper.SiteURL.Trim()) > 0)                        {                            HttpContext.Current.Response.ContentType = "image/JPEG";                            HttpContext.Current.Response.WriteFile(FileName);                        }                        else                        {                            HttpContext.Current.Response.ContentType = "image/JPEG";                            HttpContext.Current.Response.WriteFile("~/Image/forbid.png");                        }                    }                }            }            catch            { }        }    }}


然后编译 csc /t:library CustomHandler.cs

添加编译好的DLL引用到当前站点的bin文件夹下

第四步:在Web.Config 中注册这个Handler

<system.web><httpHandlers><add path="*.jpg,*.jpeg,*.gif,*.png,*.bmp" verb="*" type="CustomHandler.JpgHandler,CustomHandler" /></httpHandlers></system.web>

 


verb指的是请求此文件的方式,可以是post或get,用*代表所有访问方式。CustomHandler.JpgHandler表示命名空间和类名,CustomHandler表示程序集名。


 

 


 

原创粉丝点击