在日常开发环境中经常会遇到需要防止他人盗取自己网站的图片、文件等资源,以防大量消耗自己网站的流量及带宽。此文章概述了通过一般处理程序来防止盗链
如何使用HttpHandler
1.添加一般处理程序
2.Web.Config里面填入配置
1 2 3 4 5 6 |
</system.webSerber> <handlers> <add verb="*" path="*.aspx" type="命名空间.名字"></add> </handlers> </system.webSerber> |
相关信息说明:
verb : 包括get,post,ftp等,*为通配符
path : 路径名,表示哪些文件会受到影响
type : 处理器的名字
后台代码(Handler中)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public void ProcessRequest(HttpContext context) { //获取上次URL地址 Uri old = context.Request.UrlReferrer; //获取本次URL地址 Uri newUrl = context.Request.Url; if (old.Host == newUrl.Host) { //获取访问的文件路径 string path = context.Request.PhysicalPath; //输出此文件 context.Response.WriteFile(path); } else { //获取访问出错图片路径 string errorPath = context.Request.PhysicalApplicationPath + "Error/default.jpg"; //输出 context.Response.WriteFile(errorPath); } } |
Web.Config配置
1 2 3 4 5 6 |
</system.webSerber> <handlers> <add verb="GET" path="images/*" type="命名空间.一般处理程序的名字"></add> </handlers> </system.webSerber> |
0 条评论