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

来源:互联网 发布:js嵌套数组 编辑:程序博客网 时间:2024/06/10 18:31

原理很简单,就是对请求的文件进行判断,若图片请求的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表示程序集名。


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

在此,网站图片防盗链的方法是,通过获取Http请求头中的 Referer 标头与本网站域名比较,来判断用户是否来自本站跳转过来的 。

创建一个全局处理程序,用来处理images目录下的图片的直接请求:

using System;using System.Web; /// <summary>///DaoLian 的摘要说明/// </summary>public class DaoLian:IHttpHandler{    public bool IsReusable    {        get { return false; }    }     public void ProcessRequest(HttpContext context)    {        context.Response.ContentType = "image/jpeg";        //        //当前请求 的地址        Uri url = context.Request.Url;        Uri urlReferrer = context.Request.UrlReferrer;        if (urlReferrer != null)        {            //判断域名和端口号是否相等            if (IsSameDomain(url,urlReferrer))            {                //获取当前请求的图片的绝对路径                string path = context.Request.MapPath(context.Request.RawUrl);                context.Response.WriteFile(path);            }            else            {                //盗链图片的地址                string path = context.Request.MapPath("../daolian.jpg");                context.Response.WriteFile(path);            }        }        else        {            //盗链图片的地址            string path = context.Request.MapPath("../daolian.jpg");            context.Response.WriteFile(path);        }    }    //判断域名和端口号是否相等    bool IsSameDomain(Uri url1,Uri url2)    {        return Uri.Compare(url1, url2, UriComponents.HostAndPort, UriFormat.Unescaped, StringComparison.CurrentCultureIgnoreCase) == 0;    }}