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

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


 

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值