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表示程序集名。
- ASP.NET简单实现图片防盗链
- ASP.NET简单实现图片防盗链
- ASP.NET 实现简单的图片防盗链介绍
- ASP.NET图片防盗链
- asp.net 图片防盗链
- asp.net中利用ashx实现图片防盗链
- asp.net中利用ashx实现图片防盗链
- ASP.Net中利用ashx实现图片防盗链代码
- asp.net实现图片、文件防盗链程序
- ASP.NET 图片防盗链的实现原理分析
- ASP.NET MVC 利用IRouteHandler, IHttpHandler实现图片防盗链
- ASP.NET MVC 利用IRouteHandler, IHttpHandler实现图片防盗链
- ASP.NET 图片加水印防盗链实现代码
- ASP.NET 防盗链源码,图片防盗链
- ASP.NET 图片加水印防盗链
- ASP.NET 图片加水印防盗链
- ASP.NET 图片加水印防盗链
- ASP.NET 图片加水印防盗链
- 嵌入式linux安装sz/rz工具包
- MySQL自动关闭连接导致DBCP报错
- linux时间管理
- hadoop distcp 命令
- 找工作得失
- ASP.NET简单实现图片防盗链
- 《编程之美》——读书笔记
- 在虚拟机中安装Gitlab
- spring 事务配置方式
- Rookie零基础学java(二)第一个java程序HelloWorld(在win7和linux下)
- 代码大全 第十章 读书笔记(1)
- 编译内核 mkimage" command not found - U-Boot images will not be buil
- LCD设备驱动程序3
- 图片操作旋转等